: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): expose checks to agents and notify on new failures (#74694)
Thiago Salvatorefc76d43d6c28
diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsxindex 686c5aad3d96..32a8ea851561 100644--- a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx+++ b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx@@ -73,6 +73,10 @@ export const REALTIME_NOTIFICATION_TYPE_META: Record<string, { label: string; delabel: 'Subscription suggestions',description: 'When PostHog suggests subscribing to a dashboard you keep coming back to',},+ data_quality_check_failure: {+ label: 'Data quality check failures',+ description: 'When a data quality check on a warehouse table or view starts failing',+ },}export function NotificationTitle({diff --git a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsxindex c9392f36f8d4..4983c7dda22e 100644--- a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx+++ b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx@@ -37,6 +37,7 @@ const NOTIFICATION_TYPE_ICONS: Record<string, { Icon: ComponentType<{ className?web_analytics_digest: { Icon: IconPieChart, color: 'text-primary' },achievement_unlocked: { Icon: IconStar, color: 'text-warning' },subscription_nudge: { Icon: IconBell, color: 'text-primary' },+ data_quality_check_failure: { Icon: IconWarning, color: 'text-danger' },}export function getNotificationIcon(notificationType: string, className: string = 'size-5'): JSX.Element {diff --git a/posthog/temporal/data_modeling/activities/quality_block_materialization.py b/posthog/temporal/data_modeling/activities/quality_block_materialization.pyindex 72927999a644..25ff6413ef83 100644--- a/posthog/temporal/data_modeling/activities/quality_block_materialization.py+++ b/posthog/temporal/data_modeling/activities/quality_block_materialization.py@@ -10,6 +10,7 @@ from temporalio import activityfrom posthog.sync import database_sync_to_async_poolfrom products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobStatus, Node+from products.data_quality.backend.facade import api as data_quality_facadefrom .utils import QUALITY_BLOCKED_ERROR_PREFIX, update_node_system_properties@@ -65,6 +66,11 @@ def _block_node_and_job(inputs: QualityBlockMaterializationInputs) -> None:job.last_run_at = dt.datetime.now(dt.UTC)job.save()+ if job.saved_query_id and node.saved_query is not None:+ data_quality_facade.notify_materialization_blocked(+ inputs.team_id, str(job.saved_query_id), node.saved_query.name, inputs.blocking_failures, inputs.job_id+ )+@activity.defnasync def quality_block_materialization_activity(inputs: QualityBlockMaterializationInputs) -> None:diff --git a/products/data_catalog/skills/setting-up-data-catalog/SKILL.md b/products/data_catalog/skills/setting-up-data-catalog/SKILL.mdindex 9ca4932613ad..e21fedb83d8d 100644--- a/products/data_catalog/skills/setting-up-data-catalog/SKILL.md+++ b/products/data_catalog/skills/setting-up-data-catalog/SKILL.md@@ -100,3 +100,9 @@ Work top-down, stopping at `proposed` for everything (a human promotes later):The `refresh` parameter on `posthog:data-catalog-metric-run` is a query-cache mode, not a drift fix —it does not re-snapshot the linked insight.++## Related++Certifying a source says a human vouches for it. Proving it is _still_ correct is a separate job —+see the `authoring-data-quality-checks` skill for null, uniqueness, referential-integrity, and+freshness assertions on the same tables and views.diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.pyindex 5aa883d3ad23..35c2436a5981 100644--- a/products/data_quality/backend/facade/api.py+++ b/products/data_quality/backend/facade/api.py@@ -22,6 +22,7 @@ from ..logic.config import get_gate_config, set_gate_materialization_on_checksfrom ..logic.contracts import CompiledCheck, SubjectReffrom ..logic.errors import CheckConfigError, SubjectUnresolvableErrorfrom ..logic.health import CheckStatusRow, roll_up_health+from ..logic.notifications import notify_materialization_blockedfrom ..logic.registry import UnknownCheckTypeError, list_check_typesfrom ..logic.serialization import compute_fingerprint, from_config_entry, to_config_entryfrom ..logic.subject_access import denied_subject_names, is_subject_denied, referenced_subject_names@@ -46,6 +47,7 @@ __all__ = ["get_gate_config","is_subject_denied","list_check_types",+ "notify_materialization_blocked","quality_audit_mode","referenced_subject_names","related_subject_ref",diff --git a/products/data_quality/backend/logic/checks.py b/products/data_quality/backend/logic/checks.pyindex e1b43211a6b6..b3e623270afa 100644--- a/products/data_quality/backend/logic/checks.py+++ b/products/data_quality/backend/logic/checks.py@@ -169,8 +169,13 @@ def soft_delete_check(check: DataQualityCheck) -> None: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 checks_for_subject(+ team_id: int, subject_type: str, subject_uuid: str | UUID, include_deleted: bool = False+) -> QuerySet[DataQualityCheck]:+ queryset = DataQualityCheck.objects.for_team(team_id).filter(**_subject_fk(subject_type, subject_uuid))+ # A soft-deleted check's past runs still sit in the aggregate counts of suites it ran in, so+ # authorization over a *historical* suite has to see it too, even though it no longer runs.+ return queryset if include_deleted else queryset.filter(deleted=False)def subject_health(team_id: int, subject_type: str, subject_uuid: str | UUID) -> SubjectHealth:diff --git a/products/data_quality/backend/logic/notifications.py b/products/data_quality/backend/logic/notifications.pynew file mode 100644index 000000000000..053625c8c8e0--- /dev/null+++ b/products/data_quality/backend/logic/notifications.py@@ -0,0 +1,251 @@+"""Tell the team when a model starts failing its checks.++Only the pass-to-fail edge notifies, and only for error-severity checks. A check that keeps failing+run after run is already known about; re-notifying every run is how an inbox gets ignored.+"""++from typing import cast++import structlog++from posthog.models import Team, User+from posthog.rbac.user_access_control import UserAccessControl, access_level_satisfied_for_resource+from posthog.scopes import APIScopeObject++from products.notifications.backend.facade.api import (+ NotificationData,+ NotificationType,+ Priority,+ RecipientsResolver,+ TargetType,+ create_notification,+)++from ..facade.enums import CheckRunStatus, SubjectType+from ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from .checks import checks_for_subject+from .flags import is_data_quality_checks_enabled_for_team_id+from .subject_access import denied_subject_names, is_subject_denied, referenced_subject_names, referencing_check_types++LOGGER = structlog.get_logger(__name__)++# Object-level access controls for a warehouse table or view are keyed on the child resource; both+# inherit from the `warehouse_objects` umbrella the built-in resource-level filter checks.+_SUBJECT_RESOURCE: dict[SubjectType, APIScopeObject] = {+ SubjectType.TABLE: cast(APIScopeObject, "warehouse_table"),+ SubjectType.VIEW: cast(APIScopeObject, "warehouse_view"),+}+++class _WarehouseSubjectResolver(RecipientsResolver):+ """Drop members who must not receive this check's warehouse metadata or its failing-row count.++ Three gates on top of the built-in resource-level `warehouse_objects` filter that+ `create_notification` runs:++ - **Object-level** access to *this* table or view. The resource-level filter only asks whether a+ member can see warehouse objects at all, so a member with general warehouse access but an+ explicit denial on the subject would still receive its name, column, check type, and count.+ - **Referenced-subject** access. A `relationships` check reads a second subject and a `custom_sql`+ check reads arbitrary tables, so a failure count is an oracle over those too. A member denied+ any of the names passed in must be dropped, matching how the run-history API gates them.+ - **Query** viewer access. The body's `failed_row_count` is a count oracle over the underlying+ warehouse rows that the run-history API gates behind query access, so a member denied `query`+ must not read it from the notification either.+ """++ def __init__(+ self,+ team: Team,+ subject_type: str,+ subject_uuid: str,+ referenced_names: list[str] | None = None,+ ) -> None:+ self._team = team+ self._subject_type = subject_type+ self._subject_uuid = subject_uuid+ self._referenced_names = referenced_names or []+ # One access-control object per member, reused across both gates below (and the warehouse+ # database build the referenced-subject gate runs) so a single failing check doesn't rebuild+ # it -- and its membership, role, and access-control lookups -- once per pass.+ self._access: dict[int, UserAccessControl] = {}++ def _access_of(self, user: User) -> UserAccessControl:+ access = self._access.get(user.id)+ if access is None:+ access = UserAccessControl(user, self._team)+ self._access[user.id] = access+ return access++ def _access_controls_supported(self, user_ids: list[int]) -> bool:+ # When access controls aren't available for the org, the built-in filter lets everyone+ # through and neither gate below can deny anyone; the callers skip their per-member work.+ sample = User.objects.filter(id__in=user_ids).first()+ return sample is not None and self._access_of(sample).access_controls_supported++ def resolve(self, target_type: TargetType, target_id: str, team_id: int | None) -> list[int]:+ user_ids = super().resolve(target_type, target_id, team_id)+ user_ids = self.filter_by_access_control(user_ids, "query", self._team)+ user_ids = self._filter_by_object_access(user_ids)+ return self._filter_by_referenced_subject_access(user_ids)++ def _filter_by_object_access(self, user_ids: list[int]) -> list[int]:+ resource = _SUBJECT_RESOURCE.get(SubjectType(self._subject_type))+ if resource is None:+ return user_ids+ object_id = self._subject_uuid++ if not self._access_controls_supported(user_ids):+ return user_ids++ allowed: list[int] = []+ for user in User.objects.filter(id__in=user_ids):+ level = self._access_of(user).bulk_object_access_levels(resource, [(object_id, None)]).get(object_id)+ if level is not None and access_level_satisfied_for_resource(resource, level, "viewer"):+ allowed.append(user.id)+ return allowed++ def _filter_by_referenced_subject_access(self, user_ids: list[int]) -> list[int]:+ # The declared subject isn't the only one the count depends on: a relationships check reads+ # its target and a custom_sql check reads arbitrary tables. Drop members denied any of those,+ # matching the run-history endpoint -- resolved by name the same way the loaders resolve them.+ if not self._referenced_names:+ return user_ids++ # No warehouse access control means no denials, so skip the per-member database build the+ # denial check would otherwise run -- the same early exit the object-access gate makes.+ if not self._access_controls_supported(user_ids):+ return user_ids++ allowed: list[int] = []+ for user in User.objects.filter(id__in=user_ids):+ denied = denied_subject_names(self._team, user, self._access_of(user))+ if not any(is_subject_denied(name, denied) for name in self._referenced_names):+ allowed.append(user.id)+ return allowed+++def notify_check_started_failing(check: DataQualityCheck, failed_row_count: int | None) -> None:+ """Best-effort: a notification failure must never take down the run that produced it."""+ try:+ if not is_data_quality_checks_enabled_for_team_id(check.team_id) or check.subject_uuid is None:+ return+ team = Team.objects.get(id=check.team_id)+ create_notification(+ NotificationData(+ team_id=check.team_id,+ notification_type=NotificationType.DATA_QUALITY_CHECK_FAILURE,+ priority=Priority.NORMAL,+ title=f"Data quality check failed on {check.subject_name}",+ body=_body(check, failed_row_count),+ target_type=TargetType.TEAM,+ target_id=str(check.team_id),+ # The body names a warehouse table or view and one of its columns, so it points at+ # the subject object (not the check) and the resolver filters recipients down to+ # members with object-level access to it, plus query access for the count.+ resource_type="warehouse_objects",+ resource_id=str(check.subject_uuid),+ resolver=_WarehouseSubjectResolver(+ team,+ check.subject_type,+ str(check.subject_uuid),+ referenced_names=referenced_subject_names(team.id, check.check_type, check.config),+ ),+ )+ )+ except Exception:+ LOGGER.exception("Could not send a data quality failure notification", check_id=str(check.id))+++def notify_materialization_blocked(+ team_id: int, saved_query_id: str, view_name: str, blocking_failures: int, job_id: str+) -> None:+ """Tell the team a refresh was not published because its checks failed. Best-effort."""+ try:+ if not is_data_quality_checks_enabled_for_team_id(team_id):+ return+ team = Team.objects.get(id=team_id)+ checks = "check" if blocking_failures == 1 else "checks"+ create_notification(+ NotificationData(+ team_id=team_id,+ notification_type=NotificationType.DATA_QUALITY_CHECK_FAILURE,+ priority=Priority.NORMAL,+ title=f"Materialization of {view_name} was not published",+ body=f"{blocking_failures} data quality {checks} failed, so the previous version keeps "+ "serving. Fix the data or the checks, then materialize again.",+ target_type=TargetType.TEAM,+ target_id=str(team_id),+ resource_type="warehouse_objects",+ resource_id=saved_query_id,+ # Keyed on the blocked materialization job: the block activity can run twice when a+ # slow attempt hits its start-to-close timeout, and the unique constraint behind this+ # key collapses the retry to one notice while a genuinely new block notifies again.+ idempotency_key=f"matview-blocked-{job_id}",+ resolver=_WarehouseSubjectResolver(+ team,+ SubjectType.VIEW,+ saved_query_id,+ referenced_names=_blocking_referenced_names(team_id, saved_query_id, job_id),+ ),+ )+ )+ except Exception:+ LOGGER.exception("Could not send a materialization-blocked notification", saved_query_id=saved_query_id)+++def _blocking_referenced_names(team_id: int, saved_query_id: str, job_id: str) -> list[str]:+ """Every further subject the checks behind a blocked materialization read.++ The body's failure count aggregates those checks, so it is an oracle over everything they read,+ not just over the view the recipient is already allowed to see.++ Read off the suite's persisted check runs, not the definitions' current state. ``enabled``,+ ``severity``, ``last_status`` and ``deleted`` are all writable by anyone who can edit the view --+ including a member denied a subject the check reads, since the write path only authorizes the+ declared subject. Selecting on them would let that member edit their own denial out of this+ filter in the window between the suite finishing and this notice being written, while the count+ still counts their check. A run row is immutable, so it cannot be edited out of the set it+ belongs to. The suite is the one the blocked job triggered, so the names and the count come from+ the same batch, across every subject the batch covered.+ """+ names: set[str] = set()+ runs = (+ DataQualityCheckRun.objects.for_team(team_id)+ .filter(+ suite_run__data_modeling_job_id=job_id,+ status=CheckRunStatus.FAILED,+ # No severity on the run row, so this takes warn-severity failures too. They did not+ # block, so the set is wider than the count -- which over-filters rather than leaks.+ check_type__in=referencing_check_types(),+ )+ .select_related("quality_check")+ )+ # A run records which check ran, never the config it ran with. A definition that has since been+ # hard-deleted or re-pointed at other tables leaves nothing to enumerate, and so does a suite+ # retention already swept. Widen to every referencing check on the subject: wider than this+ # block, but it can only drop more recipients, never admit one the count would leak to.+ unbindable = not DataQualitySuiteRun.objects.for_team(team_id).filter(data_modeling_job_id=job_id).exists()+ for run in runs:+ check = run.quality_check+ if check is None or check.fingerprint != run.check_fingerprint:+ unbindable = True+ continue+ names.update(referenced_subject_names(team_id, check.check_type, check.config))+ if unbindable:+ for check in checks_for_subject(team_id, SubjectType.VIEW, saved_query_id, include_deleted=True).filter(+ check_type__in=referencing_check_types()+ ):+ names.update(referenced_subject_names(team_id, check.check_type, check.config))+ return sorted(names)+++def _body(check: DataQualityCheck, failed_row_count: int | None) -> str:+ subject = f"{check.check_type} check"+ if check.column_name:+ subject = f"{check.check_type} check on {check.subject_name}.{check.column_name}"++ if failed_row_count:+ rows = "row" if failed_row_count == 1 else "rows"+ return f"The {subject} found {failed_row_count} failing {rows}. It was passing on the previous run."+ return f"The {subject} started failing. It was passing on the previous run."diff --git a/products/data_quality/backend/logic/runner.py b/products/data_quality/backend/logic/runner.pyindex 117026a8ed22..3ee0905a0a80 100644--- a/products/data_quality/backend/logic/runner.py+++ b/products/data_quality/backend/logic/runner.py@@ -21,15 +21,21 @@ if TYPE_CHECKING:from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.scoping import team_scopefrom posthog.models.team import Team+from posthog.models.user import User-from ..facade.enums import CheckRunStatus, CheckSeverity, SubjectStatus+from ..facade.enums import CheckRunStatus, CheckSeverity, SubjectStatus, SuiteRunTriggerfrom ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom .compiler import compile_check, related_subject_reffrom .contracts import CompiledCheck, Evaluation+from .notifications import notify_check_started_failing+from .staged_audit import StagedSubjectOverride, build_staged_database+from .subject_access import check_type_reads_beyond_subjectfrom .subjects import resolve_subjectQUERY_TYPE = "data_quality_check"+STAGED_FILES_UNREADABLE = "The staged files could not be read, so this data was not audited."+@dataclass(frozen=True)class CheckOutcome:@@ -47,33 +53,36 @@ def run_check(check: DataQualityCheck,suite_run: DataQualitySuiteRun,team: Team,- database: "Database | None" = None,+ staged: StagedSubjectOverride | None = None,+ staged_database_cache: "dict[Any, Database | None] | None" = None,) -> CheckOutcome:"""Compile, execute, and persist one check. Updates the check's denormalized status.Runs under an explicit team scope because there is no request context out here, and saving acheck reads its own previous state through the fail-closed manager to build the activity log.- ``database`` overrides table resolution for write-audit-publish runs (see logic/staged_audit).+ ``staged`` redirects the subject's table at unpublished files for write-audit-publish runs (see+ logic/staged_audit); the cache is shared across a batch so each ACL posture builds one database."""started_at = datetime.now(UTC)monotonic_start = time.monotonic()- previous_status = check.last_statustry:- outcome = _execute(check, team, database)+ outcome = _execute(check, suite_run, team, staged, staged_database_cache)except Exception as err:outcome = CheckOutcome(status=CheckRunStatus.ERRORED, error=str(err))duration_ms = int((time.monotonic() - monotonic_start) * 1000)with team_scope(team.id):_record_run(check, suite_run, outcome, started_at, duration_ms)+ became_failing = (+ outcome.status is CheckRunStatus.FAILED+ and check.severity == CheckSeverity.ERROR+ and _claim_failing_transition(check)+ )_update_check(check, outcome)- became_failing = (- outcome.status is CheckRunStatus.FAILED- and previous_status != CheckRunStatus.FAILED- and check.severity == CheckSeverity.ERROR- )+ if became_failing:+ notify_check_started_failing(check, outcome.failed_row_count)return replace(outcome, became_failing=became_failing)@@ -91,7 +100,99 @@ def record_unrunnable_check(return outcome-def _execute(check: DataQualityCheck, team: Team, database: "Database | None" = None) -> CheckOutcome:+def _claim_failing_transition(check: DataQualityCheck) -> bool:+ """Whether this run is the one that moved the check into failing.++ Runs of the same check can overlap -- a manual run alongside the scheduled one -- and comparing+ against a status read in Python lets both of them see the same passing value and notify. The+ conditional update lets exactly one flip the row, so the pass-to-fail edge notifies once. Must+ run before ``_update_check`` writes the new status, or there is nothing left to claim.+ """+ return (+ DataQualityCheck.objects.for_team(check.team_id)+ .filter(id=check.id)+ .exclude(last_status=CheckRunStatus.FAILED)+ .update(last_status=CheckRunStatus.FAILED)+ == 1+ )+++@dataclass(frozen=True)+class _Authorization:+ """How one run's query executes against warehouse access control."""++ run_as: User | None+ bypass: bool+++def _authorize(check: DataQualityCheck, suite_run: DataQualitySuiteRun) -> _Authorization | None:+ """How a run's query must execute so HogQL enforces the right warehouse access control.++ A check that reads beyond its declared subject -- ``custom_sql`` runs arbitrary HogQL,+ ``relationships`` also reads its target subject -- can otherwise be used to read a failing-row+ count over a table the caller was denied. The defense is to run the query as a user whose+ warehouse ACL HogQL will apply, so a denied object errors the check instead of leaking.++ - Manual runs execute as their initiator.+ - Automated runs (materialization, source sync) have no initiator. A check constrained to only+ its declared subject exposes nothing the definition doesn't already name, so the service+ bypass is safe. A check that reads a further subject has no such guarantee, so it executes as+ the check's author; with no author there is nobody to authorize against, and returning+ ``None`` errors the run rather than bypassing the ACL over a subject the author may since+ have lost access to.+ """+ if suite_run.trigger == SuiteRunTrigger.MANUAL:+ return _Authorization(run_as=suite_run.created_by, bypass=suite_run.created_by is None)+ if not check_type_reads_beyond_subject(check.check_type):+ return _Authorization(run_as=None, bypass=True)+ if check.created_by is None:+ return None+ return _Authorization(run_as=check.created_by, bypass=False)+++def _staged_database(+ team: Team,+ staged: StagedSubjectOverride,+ authorization: _Authorization,+ cache: "dict[Any, Database | None] | None",+) -> "Database | None":+ """The staged-override database for this run's ACL posture, built once per posture per batch."""+ key = authorization.run_as.id if authorization.run_as is not None else "__bypass__"+ if cache is not None and key in cache:+ return cache[key]+ database = build_staged_database(+ team,+ staged.saved_query_id,+ staged.queryable_folder,+ user=authorization.run_as,+ bypass_warehouse_access_control=authorization.bypass,+ )+ if cache is not None:+ cache[key] = database+ return database+++def staged_subject_is_reachable(+ team: Team,+ staged: StagedSubjectOverride,+ cache: "dict[Any, Database | None] | None" = None,+) -> bool:+ """Whether the staged files can be repointed at all, before any check runs.++ Independent of which user a check executes as, so a batch settles it once. Shares the runner's+ cache, so the database built here is the one the service-bypass runs reuse.+ """+ return _staged_database(team, staged, _Authorization(run_as=None, bypass=True), cache) is not None+++def _execute(+ check: DataQualityCheck,+ suite_run: DataQualitySuiteRun,+ team: Team,+ staged: StagedSubjectOverride | None = None,+ staged_database_cache: "dict[Any, Database | None] | None" = None,+) -> CheckOutcome:+ # A hard-deleted subject nulls the FK; there is no id left to resolve.if check.subject_uuid is None:check.subject_status = SubjectStatus.ORPHANEDreturn CheckOutcome(status=CheckRunStatus.SKIPPED, error="The subject was deleted.")@@ -104,6 +205,13 @@ def _execute(check: DataQualityCheck, team: Team, database: "Database | None" =check.subject_status = SubjectStatus.ACTIVEcheck.subject_name = subject.name+ authorization = _authorize(check, suite_run)+ if authorization is None:+ return CheckOutcome(+ status=CheckRunStatus.ERRORED,+ error="An automated check that reads another subject needs an author to authorize its warehouse access.",+ )+related = related_subject_ref(check.check_type, check.config)compiled = compile_check(check_type=check.check_type,@@ -112,6 +220,12 @@ def _execute(check: DataQualityCheck, team: Team, database: "Database | None" =config=check.config,related_subject=resolve_subject(team.id, *related) if related else None,)+ database = _staged_database(team, staged, authorization, staged_database_cache) if staged is not None else None+ if staged is not None and database is None:+ # Falling back to the unmodified database would read the live view and rule on data the+ # publish would not write, so a staged run that cannot repoint errors instead.+ return CheckOutcome(status=CheckRunStatus.ERRORED, error=STAGED_FILES_UNREADABLE)+with tags_context(product=Product.DATA_QUALITY,feature=Feature.DATA_QUALITY_CHECK,@@ -120,15 +234,30 @@ def _execute(check: DataQualityCheck, team: Team, database: "Database | None" =data_quality_subject_type=subject.subject_type,data_quality_subject_id=subject.subject_uuid,):+ # The query runs as the user whose warehouse ACL HogQL should enforce (see _authorize). The+ # service-level bypass is only used where there is no actor and the query is constrained to+ # the check's declared subject, so it can't reach a warehouse object the definition doesn't+ # already name.if database is not None:response = execute_hogql_query(query=compiled.query,team=team,query_type=QUERY_TYPE,- context=HogQLContext(team_id=team.pk, database=database),+ context=HogQLContext(+ team_id=team.pk,+ user=authorization.run_as,+ database=database,+ bypass_warehouse_access_control=authorization.bypass,+ ),)else:- response = execute_hogql_query(query=compiled.query, team=team, query_type=QUERY_TYPE)+ response = execute_hogql_query(+ query=compiled.query,+ team=team,+ query_type=QUERY_TYPE,+ user=authorization.run_as,+ bypass_warehouse_access_control=authorization.bypass,+ )return _interpret(compiled, check.config, response.results, response.columns or [])diff --git a/products/data_quality/backend/logic/staged_audit.py b/products/data_quality/backend/logic/staged_audit.pyindex 5ffbe6341dfc..1b82d72a9e18 100644--- a/products/data_quality/backend/logic/staged_audit.py+++ b/products/data_quality/backend/logic/staged_audit.py@@ -1,5 +1,6 @@"""Point a subject's table at staged (unpublished) files, for write-audit-publish check runs."""+from dataclasses import dataclassfrom typing import TYPE_CHECKINGfrom uuid import UUID@@ -11,20 +12,43 @@ from products.data_modeling.backend.facade import api as data_modeling_facadeif TYPE_CHECKING:from posthog.models.team import Team+ from posthog.models.user import User-def build_staged_database(team: "Team", saved_query_id: str | UUID, staged_queryable_folder: str) -> Database | None:- """None means there is no materialized table to repoint.+@dataclass(frozen=True)+class StagedSubjectOverride:+ """Where a write-audit-publish run should read the subject from instead of the published table."""- Callers must not fall back to the unmodified database, which reads the live view and so rules- on data the publish would not write.+ saved_query_id: str+ queryable_folder: str+++def build_staged_database(+ team: "Team",+ saved_query_id: str | UUID,+ staged_queryable_folder: str,+ user: "User | None" = None,+ bypass_warehouse_access_control: bool = False,+) -> Database | None:+ """A database whose subject table reads the staged folder instead of the published one.++ Built with the run's ACL posture (the runner's ``_authorize``), so a staged audit enforces the+ same warehouse access control an unstaged run would.++ None means there is no materialized table to repoint. Callers must not fall back to the+ unmodified database, which reads the live view and so rules on data the publish would not write."""summary = data_modeling_facade.get_saved_query_summary(team.pk, saved_query_id)if summary is None:return Nonemodifiers = create_default_modifiers_for_team(team)- database = Database.create_for(team=team, modifiers=modifiers)+ database = Database.create_for(+ team=team,+ user=user,+ modifiers=modifiers,+ bypass_warehouse_access_control=bypass_warehouse_access_control,+ )try:table = database.get_table(summary.name)except Exception:diff --git a/products/data_quality/backend/logic/subject_access.py b/products/data_quality/backend/logic/subject_access.pyindex 573b6706f665..c442e9989739 100644--- a/products/data_quality/backend/logic/subject_access.py+++ b/products/data_quality/backend/logic/subject_access.py@@ -12,7 +12,8 @@ from typing import TYPE_CHECKING, Any, Optionalfrom posthog.hogql.database.database import Databasefrom posthog.hogql.database.schema.information_schema import _references_denied_table-from .registry import get_spec+from .registry import all_specs, get_spec+from .spec import CheckTypeSpecfrom .subjects import resolve_subjectif TYPE_CHECKING:@@ -36,6 +37,44 @@ def is_subject_denied(subject_name: str, denied: set[str]) -> bool:return _references_denied_table([subject_name], denied)+# A check type reads beyond its declared subject only if it overrides one of these hooks: a+# ``relationships`` check names a target subject, a ``custom_sql`` query selects arbitrary tables.+# Derived from the specs rather than hard-coded so a new referencing type can't silently slip the net.+_REFERENCING_CHECK_TYPES: frozenset[str] = frozenset(+ str(spec.type_name)+ for spec in all_specs()+ if type(spec).related_subject_ref is not CheckTypeSpec.related_subject_ref+ or type(spec).referenced_table_names is not CheckTypeSpec.referenced_table_names+)+++def check_type_reads_beyond_subject(check_type: str) -> bool:+ """Whether this check type can read warehouse objects other than its declared subject.++ Used to fail closed when a run's definition was hard-deleted: without the config we can no longer+ enumerate the referenced subjects, so a ``relationships`` or ``custom_sql`` run must be treated as+ if it could touch a denied one."""+ return check_type in _REFERENCING_CHECK_TYPES+++def referencing_check_types() -> frozenset[str]:+ """The check types that read beyond their declared subject (``relationships``, ``custom_sql``).++ A cheap pre-filter so a denied-reference scan only parses the config of checks that can carry one,+ rather than every check on the team."""+ return _REFERENCING_CHECK_TYPES+++def check_reads_denied_subject(team_id: int, check_type: str, config: dict[str, Any], denied: set[str]) -> bool:+ """Whether a check reads any subject *besides its declared one* that the caller is denied.++ The single test the health rollup and suite-summary guards share, so the REST endpoint and the+ ``information_schema`` tables stay in lock-step about which referencing checks a member may see."""+ if not denied:+ return False+ return any(is_subject_denied(name, denied) for name in referenced_subject_names(team_id, check_type, config))++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.diff --git a/products/data_quality/backend/temporal/activities/run_check_batch.py b/products/data_quality/backend/temporal/activities/run_check_batch.pyindex dbc97735ff72..8d0ee87a1b3f 100644--- a/products/data_quality/backend/temporal/activities/run_check_batch.py+++ b/products/data_quality/backend/temporal/activities/run_check_batch.py@@ -10,15 +10,13 @@ from posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_loggerfrom ...facade.enums import CheckRunStatus, CheckSeverity-from ...logic.runner import record_unrunnable_check, run_check-from ...logic.staged_audit import build_staged_database+from ...logic.runner import STAGED_FILES_UNREADABLE, record_unrunnable_check, run_check, staged_subject_is_reachable+from ...logic.staged_audit import StagedSubjectOverridefrom ...models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom ..contracts import BatchOutcome, RunCheckBatchInputsLOGGER = get_logger(__name__)-STAGED_FILES_UNREADABLE = "The staged files could not be read, so this data was not audited."-@activity.defnasync def run_check_batch_activity(inputs: RunCheckBatchInputs) -> BatchOutcome:@@ -51,17 +49,23 @@ def _run_batch(inputs: RunCheckBatchInputs) -> BatchOutcome:suite_run=suite_run, quality_check_id__in=inputs.check_ids).delete()- staged_database = None+ staged = None+ staged_database_cache: dict = {}if inputs.staged_queryable_folder and inputs.staged_saved_query_id:- staged_database = build_staged_database(team, inputs.staged_saved_query_id, inputs.staged_queryable_folder)- if staged_database is None:+ staged = StagedSubjectOverride(+ saved_query_id=inputs.staged_saved_query_id,+ queryable_folder=inputs.staged_queryable_folder,+ )+ if not staged_subject_is_reachable(team, staged, staged_database_cache):return _record_unaudited_batch(checks, suite_run, team)counts: Counter[str] = Counter()failed_blocking = 0newly_failing: list[str] = []for check in checks:- result = run_check(check, suite_run, team, database=staged_database)+ # run_check records a compile or query failure as an errored run rather than raising: one+ # broken check must not fail the activity and take its whole batch down with it.+ result = run_check(check, suite_run, team, staged=staged, staged_database_cache=staged_database_cache)counts[result.status] += 1if result.status is CheckRunStatus.FAILED and check.severity == CheckSeverity.ERROR:failed_blocking += 1diff --git a/products/data_quality/backend/tests/test_notifications.py b/products/data_quality/backend/tests/test_notifications.pynew file mode 100644index 000000000000..168fffb916b1--- /dev/null+++ b/products/data_quality/backend/tests/test_notifications.py@@ -0,0 +1,361 @@+from uuid import uuid4++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.cache import cache++from parameterized import parameterized++from posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership, User++from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.data_quality.backend.facade.enums import (+ CheckRunStatus,+ CheckSeverity,+ CheckType,+ SubjectType,+ SuiteRunTrigger,+)+from products.data_quality.backend.logic.notifications import (+ _blocking_referenced_names,+ _WarehouseSubjectResolver,+ notify_materialization_blocked,+)+from products.data_quality.backend.logic.runner import run_check+from products.data_quality.backend.logic.subject_access import referenced_subject_names+from products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from products.notifications.backend.facade.enums import TargetType++from ee.models.rbac.access_control import AccessControl++RUNNER_QUERY = "products.data_quality.backend.logic.runner.execute_hogql_query"+CREATE_NOTIFICATION = "products.data_quality.backend.logic.notifications.create_notification"+++class _Response:+ def __init__(self, failure_count: int) -> None:+ self.columns = ["failure_count", "observed_value"]+ self.results = [[failure_count, failure_count]]+++class TestDataQualityNotifications(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ flag = patch(+ "products.data_quality.backend.logic.notifications.is_data_quality_checks_enabled_for_team_id",+ return_value=True,+ )+ flag.start()+ self.addCleanup(flag.stop)+ self.view = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="orders", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ self.suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger=SuiteRunTrigger.MANUAL+ )++ def _check(self, **kwargs) -> DataQualityCheck:+ defaults = {+ "team": self.team,+ "subject_type": SubjectType.VIEW,+ "saved_query_id": self.view.id,+ "subject_name": "orders",+ "check_type": CheckType.NOT_NULL,+ "column_name": "customer_id",+ "fingerprint": uuid4().hex,+ }+ return DataQualityCheck.objects.for_team(self.team.id).create(**{**defaults, **kwargs})++ def _resolver_for(self, check: DataQualityCheck) -> _WarehouseSubjectResolver:+ return _WarehouseSubjectResolver(+ self.team,+ check.subject_type,+ str(check.subject_uuid),+ referenced_names=referenced_subject_names(self.team.id, check.check_type, check.config),+ )++ @parameterized.expand(+ [+ ("first_failure", "", CheckSeverity.ERROR, 3, 1),+ ("still_failing", CheckRunStatus.FAILED, CheckSeverity.ERROR, 3, 0),+ ("recovered_then_failed_again", CheckRunStatus.PASSED, CheckSeverity.ERROR, 3, 1),+ ("warn_severity_failure", "", CheckSeverity.WARN, 3, 0),+ ("passing", "", CheckSeverity.ERROR, 0, 0),+ ("recovery", CheckRunStatus.FAILED, CheckSeverity.ERROR, 0, 0),+ ]+ )+ def test_only_a_pass_to_fail_edge_on_an_error_check_notifies(+ self, _name, previous_status: str, severity: CheckSeverity, failure_count: int, expected_calls: int+ ) -> None:+ check = self._check(last_status=previous_status, severity=severity)++ with patch(CREATE_NOTIFICATION) as create_notification:+ with patch(RUNNER_QUERY, return_value=_Response(failure_count)):+ run_check(check, self.suite_run, self.team)++ assert create_notification.call_count == expected_calls++ def test_the_notification_names_the_subject_and_the_failing_row_count(self) -> None:+ check = self._check()++ with patch(CREATE_NOTIFICATION) as create_notification:+ with patch(RUNNER_QUERY, return_value=_Response(4)):+ run_check(check, self.suite_run, self.team)++ payload = create_notification.call_args.args[0]+ assert payload.title == "Data quality check failed on orders"+ assert "4 failing rows" in payload.body+ # The notification points at the warehouse subject object, not the check row.+ assert payload.resource_id == str(check.subject_uuid)++ def test_recipients_are_filtered_to_members_who_can_see_warehouse_objects(self) -> None:+ # The body names a table and column, so it must not reach members denied warehouse access.+ check = self._check()++ with patch(CREATE_NOTIFICATION) as create_notification:+ with patch(RUNNER_QUERY, return_value=_Response(4)):+ run_check(check, self.suite_run, self.team)++ assert create_notification.call_args.args[0].resource_type == "warehouse_objects"++ @patch("products.notifications.backend.resolvers.UserAccessControl")+ def test_members_without_query_access_do_not_get_the_failing_row_count(self, mock_uac_cls) -> None:+ # The body's failing-row count is a count oracle over warehouse rows the run-history API gates+ # behind query access, so a member with warehouse access but no query access must be dropped.+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save()+ denied = User.objects.create_and_join(self.organization, "[email protected]", "password")++ class FakeUAC:+ def __init__(self, user, team) -> None:+ self._user_id = user.id++ @property+ def access_controls_supported(self) -> bool:+ return True++ def check_access_level_for_resource(self, resource, level) -> bool:+ # Everyone can see warehouse objects; only the denied user lacks query access.+ return resource != "query" or self._user_id != denied.id++ mock_uac_cls.side_effect = FakeUAC++ check = self._check()+ resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)++ assert self.user.id in resolved+ assert denied.id not in resolved++ def test_members_denied_the_subject_object_do_not_get_the_notification(self) -> None:+ # A member with general warehouse and query access but an explicit denial on THIS view must+ # not receive its name, column, or failing-row count -- the built-in resource-level filter+ # only asks whether they can see warehouse objects at all.+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save()+ allowed = User.objects.create_and_join(self.organization, "[email protected]", "password")+ blocked = User.objects.create_and_join(self.organization, "[email protected]", "password")+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_view",+ resource_id=str(self.view.id),+ organization_member=OrganizationMembership.objects.get(organization=self.organization, user=blocked),+ access_level="none",+ )+ check = self._check()++ resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)++ assert allowed.id in resolved+ assert blocked.id not in resolved++ def _deny_view_for_member(self, view, member: User) -> None:+ # Deny one member object-level access to a view the way the HogQL database sees it, so+ # denied_subject_names() picks it up -- the same setup the REST run-history tests use.+ 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(view.id),+ organization_member=OrganizationMembership.objects.get(organization=self.organization, user=member),+ access_level="none",+ )+ flag = patch(+ "posthog.hogql.database.database.feature_enabled_or_false",+ side_effect=lambda name, *a, **k: name == "hogql-warehouse-access-control",+ )+ flag.start()+ self.addCleanup(flag.stop)+ cache.clear()++ @parameterized.expand(+ [+ ("custom_sql", CheckType.CUSTOM_SQL, "", {"query": "SELECT 1 FROM orders"}),+ ("relationships", CheckType.RELATIONSHIPS, "customer_id", None),+ ]+ )+ def test_members_denied_a_referenced_subject_do_not_get_the_notification(+ self, _name, check_type, column_name, config+ ) -> None:+ # A relationships check reads a target subject and a custom_sql check reads arbitrary tables,+ # so the failing-row count is a count oracle over those too. A member allowed the declared+ # subject ("customers") but denied a referenced one ("orders") must be dropped, matching the+ # run-history endpoint -- while an admin, who is denied nothing, still receives it.+ customers = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ if config is None:+ config = {"to_subject_type": SubjectType.VIEW, "to_subject_uuid": str(self.view.id), "to_column": "id"}+ blocked = User.objects.create_and_join(self.organization, "[email protected]", "password")+ self._deny_view_for_member(self.view, blocked)+ check = self._check(+ saved_query_id=customers.id,+ subject_name="customers",+ check_type=check_type,+ column_name=column_name,+ config=config,+ )++ resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)++ assert self.user.id in resolved+ assert blocked.id not in resolved++ def test_members_denied_a_referenced_subject_do_not_get_the_blocked_materialization_count(self) -> None:+ # The blocked-materialization body counts the checks that failed, and one of them reads a+ # second view, so the count is an oracle over that view too. A member allowed the view being+ # materialized but denied the referenced one must be dropped.+ customers = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ blocked = User.objects.create_and_join(self.organization, "[email protected]", "password")+ self._deny_view_for_member(self.view, blocked)+ self._check(+ saved_query_id=customers.id,+ subject_name="customers",+ check_type=CheckType.RELATIONSHIPS,+ config={"to_subject_type": SubjectType.VIEW, "to_subject_uuid": str(self.view.id), "to_column": "id"},+ severity=CheckSeverity.ERROR,+ last_status=CheckRunStatus.FAILED,+ )++ with patch(CREATE_NOTIFICATION) as create_notification:+ notify_materialization_blocked(self.team.id, str(customers.id), "customers", 1, str(uuid4()))++ resolver = create_notification.call_args.args[0].resolver+ resolved = resolver.resolve(TargetType.TEAM, str(self.team.id), self.team.id)+ assert self.user.id in resolved+ assert blocked.id not in resolved++ def _blocking_relationships_check(self) -> tuple[DataWarehouseSavedQuery, str, DataQualityCheck]:+ # A materialization of "customers" blocked by a relationships check reading "orders", with the+ # suite run and check run the block left behind -- the state the notification reads.+ customers = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ check = self._check(+ saved_query_id=customers.id,+ subject_name="customers",+ check_type=CheckType.RELATIONSHIPS,+ column_name="",+ config={"to_subject_type": SubjectType.VIEW, "to_subject_uuid": str(self.view.id), "to_column": "id"},+ severity=CheckSeverity.ERROR,+ last_status=CheckRunStatus.FAILED,+ )+ job_id = str(uuid4())+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger=SuiteRunTrigger.MATERIALIZATION, data_modeling_job_id=job_id+ )+ DataQualityCheckRun.objects.for_team(self.team.id).create(+ team=self.team,+ quality_check=check,+ suite_run=suite_run,+ subject_type=SubjectType.VIEW,+ subject_uuid=customers.id,+ subject_name="customers",+ check_type=CheckType.RELATIONSHIPS,+ check_fingerprint=check.fingerprint,+ status=CheckRunStatus.FAILED,+ failed_row_count=2,+ )+ return customers, job_id, check++ @parameterized.expand(+ [+ ("untouched", {}),+ ("disabled_after_the_suite", {"enabled": False}),+ ("downgraded_after_the_suite", {"severity": CheckSeverity.WARN}),+ ("recovered_after_the_suite", {"last_status": CheckRunStatus.PASSED}),+ ("soft_deleted_after_the_suite", {"deleted": True}),+ ]+ )+ def test_editing_a_check_after_its_suite_cannot_drop_it_from_the_recipient_filter(self, _name, edit: dict) -> None:+ # The write path authorizes the declared subject only, so a member denied a referenced table+ # can still edit a check that reads it. Were the filter selected from enabled/severity/+ # last_status/deleted, that member could edit their own denial out of it between the suite+ # finishing and this notice being written, and still receive a count their check fed.+ customers, job_id, check = self._blocking_relationships_check()+ if edit:+ DataQualityCheck.objects.for_team(self.team.id).filter(pk=check.pk).update(**edit)++ assert _blocking_referenced_names(self.team.id, str(customers.id), job_id) == ["orders"]++ def test_a_failure_from_another_job_does_not_gate_this_blocks_recipients(self) -> None:+ # The counterpart: binding to the blocking suite must also stay narrow. A check that failed+ # under some earlier job never fed this count, so its referenced subjects must not+ # permanently drop members denied them from every later notice for the view.+ customers, _job_id, _check = self._blocking_relationships_check()+ later_job_id = str(uuid4())+ DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger=SuiteRunTrigger.MATERIALIZATION, data_modeling_job_id=later_job_id+ )++ assert _blocking_referenced_names(self.team.id, str(customers.id), later_job_id) == []++ def test_a_block_with_no_resolvable_suite_falls_back_to_every_referencing_check(self) -> None:+ # Retention sweeps suite runs, and a definition can be hard-deleted or re-pointed. With+ # nothing left to bind the count to, the filter widens to every referencing check on the+ # subject rather than sending unfiltered.+ customers = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ self._check(+ saved_query_id=customers.id,+ subject_name="customers",+ check_type=CheckType.RELATIONSHIPS,+ column_name="",+ config={"to_subject_type": SubjectType.VIEW, "to_subject_uuid": str(self.view.id), "to_column": "id"},+ enabled=False,+ deleted=True,+ )++ assert _blocking_referenced_names(self.team.id, str(customers.id), str(uuid4())) == ["orders"]++ def test_a_blocked_run_carries_a_dedupe_key_stable_per_job(self) -> None:+ # The block activity runs twice when a slow attempt hits its start-to-close timeout; both+ # attempts share the job id, so the notice carries a key stable across retries -- the unique+ # constraint behind it collapses the retry to one notice -- while a genuinely new block+ # (a different job) gets a new key and notifies again.+ job_id = str(uuid4())+ with patch(CREATE_NOTIFICATION) as create_notification:+ notify_materialization_blocked(self.team.id, str(self.view.id), "orders", 1, job_id)+ notify_materialization_blocked(self.team.id, str(self.view.id), "orders", 1, job_id)+ notify_materialization_blocked(self.team.id, str(self.view.id), "orders", 1, str(uuid4()))++ keys = [call.args[0].idempotency_key for call in create_notification.call_args_list]+ assert keys[0] is not None+ assert keys[0] == keys[1]+ assert keys[0] != keys[2]++ def test_a_notification_failure_does_not_fail_the_run(self) -> None:+ check = self._check()++ with patch(CREATE_NOTIFICATION, side_effect=RuntimeError("notifications down")):+ with patch(RUNNER_QUERY, return_value=_Response(4)):+ outcome = run_check(check, self.suite_run, self.team)++ assert outcome.status == CheckRunStatus.FAILEDdiff --git a/products/data_quality/backend/tests/test_run_check_suite.py b/products/data_quality/backend/tests/test_run_check_suite.pyindex 608aa6cdaf0a..9618dc136a9a 100644--- a/products/data_quality/backend/tests/test_run_check_suite.py+++ b/products/data_quality/backend/tests/test_run_check_suite.py@@ -132,7 +132,7 @@ class TestCheckSuiteActivities(BaseTest):erroring = self._check(check_type=CheckType.CUSTOM_SQL, column_name="", config={"query": "nonsense ((("})prepared = self._prepare()- def _fake_query(query, team, query_type):+ def _fake_query(query, team, query_type, **kwargs):failure_count = 4 if "total" in str(query.to_hogql()) else 0return _Response(["failure_count", "observed_value"], [failure_count, failure_count])diff --git a/products/data_quality/backend/tests/test_runner.py b/products/data_quality/backend/tests/test_runner.pyindex 9900c1ffcd01..401e7252216e 100644--- a/products/data_quality/backend/tests/test_runner.py+++ b/products/data_quality/backend/tests/test_runner.py@@ -157,6 +157,71 @@ class TestCheckRunner(BaseTest):run = DataQualityCheckRun.objects.for_team(self.team.id).get(quality_check=check)assert run.compiled_query == "SELECT * FROM orders WHERE isNull(customer_id)"+ @parameterized.expand(+ [+ # A manual run executes as its initiator so HogQL enforces that user's warehouse access:+ # a custom_sql check can't reach an object its author was denied.+ ("manual_with_user", SuiteRunTrigger.MANUAL, True, False),+ # No actor to authorize against, so the bypass stays -- otherwise every warehouse check errors.+ ("manual_without_user", SuiteRunTrigger.MANUAL, False, True),+ ("materialization_ignores_creator", SuiteRunTrigger.MATERIALIZATION, True, True),+ ]+ )+ def test_warehouse_access_control_is_enforced_only_for_user_initiated_runs(+ self, _name, trigger: SuiteRunTrigger, with_user: bool, expected_bypass: bool+ ) -> None:+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger=trigger, created_by=self.user if with_user else None+ )+ check = self._check()+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [0, 0])) as query:+ run_check(check, suite_run, self.team)++ assert query.call_args.kwargs["bypass_warehouse_access_control"] is expected_bypass+ assert query.call_args.kwargs["user"] == (None if expected_bypass else self.user)++ def _referencing_check(self, check_type: CheckType, created_by) -> DataQualityCheck:+ # Both types read beyond their declared subject: custom_sql over arbitrary SQL, relationships+ # over a target subject. The relationships target must resolve so the check compiles.+ if check_type == CheckType.RELATIONSHIPS:+ target = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ config = {"to_subject_type": SubjectType.VIEW, "to_subject_uuid": str(target.id), "to_column": "id"}+ return self._check(check_type=check_type, column_name="customer_id", config=config, created_by=created_by)+ return self._check(check_type=check_type, column_name="", config={"query": "select 1"}, created_by=created_by)++ @parameterized.expand([("custom_sql", CheckType.CUSTOM_SQL), ("relationships", CheckType.RELATIONSHIPS)])+ def test_an_automated_referencing_check_runs_as_its_author(self, _name, check_type: CheckType) -> None:+ # An automated run has no initiator, but a check that reads beyond its declared subject isn't+ # constrained to it, so it executes as the check's author to enforce that user's warehouse ACL+ # rather than bypassing it -- otherwise a check outlives its author's access to what it reads.+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger=SuiteRunTrigger.MATERIALIZATION+ )+ check = self._referencing_check(check_type, created_by=self.user)+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [0, 0])) as query:+ run_check(check, suite_run, self.team)++ assert query.call_args.kwargs["bypass_warehouse_access_control"] is False+ assert query.call_args.kwargs["user"] == self.user++ @parameterized.expand([("custom_sql", CheckType.CUSTOM_SQL), ("relationships", CheckType.RELATIONSHIPS)])+ def test_an_automated_referencing_check_without_an_author_errors_without_running(+ self, _name, check_type: CheckType+ ) -> None:+ # No initiator and no author means nobody to authorize the referenced subject against, so the+ # run is errored rather than executed with the warehouse ACL bypassed.+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger=SuiteRunTrigger.MATERIALIZATION+ )+ check = self._referencing_check(check_type, created_by=None)+ with patch(RUNNER_QUERY) as query:+ outcome = run_check(check, suite_run, self.team)++ query.assert_not_called()+ assert outcome.status == CheckRunStatus.ERRORED+@parameterized.expand([("first_failure", "", CheckSeverity.ERROR, True),@@ -175,3 +240,15 @@ class TestCheckRunner(BaseTest):assert outcome.became_failing is expectedcheck.refresh_from_db()assert check.last_status == CheckRunStatus.FAILED++ def test_an_overlapping_run_does_not_claim_the_same_failing_transition(self) -> None:+ # Stands in for a manual run racing the scheduled one: this run still holds the passing+ # status it loaded, but the row already moved to failing, so it must not notify a second time.+ check = self._check(last_status=CheckRunStatus.PASSED, severity=CheckSeverity.ERROR)+ DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id).update(last_status=CheckRunStatus.FAILED)++ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [3, 3])):+ outcome = run_check(check, self.suite_run, self.team)++ assert outcome.status == CheckRunStatus.FAILED+ assert outcome.became_failing is Falsediff --git a/products/data_quality/mcp/tools.yaml b/products/data_quality/mcp/tools.yamlnew file mode 100644index 000000000000..fe4aa2bfa42f--- /dev/null+++ b/products/data_quality/mcp/tools.yaml@@ -0,0 +1,260 @@+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.+# The tool list and operation IDs are kept in sync automatically:+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all+#+# To enable a tool, set enabled: true and add required scopes + annotations.+# All other fields (title, description, enrich_url, etc.) are yours to configure.+category: Data quality+feature: data_quality+url_prefix: /+ui_apps: {}+tools:+ data-quality-check-create-on-table:+ operation: warehouse_tables_checks_create+ enabled: true+ scopes:+ - warehouse_table:write+ - query:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Create a data quality check on a table+ description: |+ Add a dbt-test-style assertion to a synced warehouse table; the table's id is the table_id+ path parameter. A check passes when it finds zero failing rows.++ Query `system.information_schema.data_quality_checks` first — re-creating an identical check is a no-op,+ but a near-duplicate with different config is noise for whoever reviews the results.++ Prefer a generic type over custom_sql. Config per type:+ - not_null, unique: no config; set column_name.+ - accepted_values: {"values": ["paid", "refunded"]}; set column_name.+ - relationships: {"to_subject_type": "table", "to_subject_uuid": "<uuid>", "to_column": "id"}; set+ column_name.+ - row_count: {"min": 1} and/or {"max": 1000000}; no column_name.+ - freshness: {"max_age_minutes": 60}; set column_name to a timestamp column.+ - custom_sql: {"query": "select 1 from orders where total < 0"}; every row it returns is a failure.++ Use severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but+ not acting on. Checks run automatically after each sync of the table; there is nothing to schedule.+ inject_body:+ created_source: ai_generated+ feature_flag: data-quality-checks+ data-quality-check-create-on-view:+ operation: warehouse_saved_queries_checks_create+ enabled: true+ scopes:+ - warehouse_view:write+ - query:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Create a data quality check on a view+ description: |+ Add a dbt-test-style assertion to a saved query (view or materialized view); the view's id is+ the saved_query_id path parameter. A check passes when it finds zero failing rows.++ Query `system.information_schema.data_quality_checks` first — re-creating an identical check is a no-op,+ but a near-duplicate with different config is noise for whoever reviews the results.++ Prefer a generic type over custom_sql. Config per type:+ - not_null, unique: no config; set column_name.+ - accepted_values: {"values": ["paid", "refunded"]}; set column_name.+ - relationships: {"to_subject_type": "table", "to_subject_uuid": "<uuid>", "to_column": "id"}; set+ column_name.+ - row_count: {"min": 1} and/or {"max": 1000000}; no column_name.+ - freshness: {"max_age_minutes": 60}; set column_name to a timestamp column.+ - custom_sql: {"query": "select 1 from orders where total < 0"}; every row it returns is a failure.++ Use severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but+ not acting on. Checks run automatically when the view refreshes; there is nothing to schedule.+ inject_body:+ created_source: ai_generated+ feature_flag: data-quality-checks+ data-quality-check-delete-on-table:+ operation: warehouse_tables_checks_destroy+ enabled: true+ scopes:+ - warehouse_table:write+ - query:read+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Delete a data quality check on a table+ description: >+ Delete a check. The API soft-deletes it, so its run history stays queryable in+ system.information_schema.data_quality_check_runs and past failures can still be dated.+ feature_flag: data-quality-checks+ data-quality-check-delete-on-view:+ operation: warehouse_saved_queries_checks_destroy+ enabled: true+ scopes:+ - warehouse_view:write+ - query:read+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Delete a data quality check on a view+ description: >+ Delete a check. The API soft-deletes it, so its run history stays queryable in+ system.information_schema.data_quality_check_runs and past failures can still be dated.+ feature_flag: data-quality-checks+ data-quality-check-results-on-table:+ operation: warehouse_tables_checks_runs_list+ enabled: true+ scopes:+ - warehouse_table:read+ - query:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Recent results of a data quality check on a table+ description: >+ The check's newest runs, including the failing-row count and the compiled HogQL that selects the offending+ rows — re-run that query to investigate a failure.+ feature_flag: data-quality-checks+ data-quality-check-results-on-view:+ operation: warehouse_saved_queries_checks_runs_list+ enabled: true+ scopes:+ - warehouse_view:read+ - query:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Recent results of a data quality check on a view+ description: >+ The check's newest runs, including the failing-row count and the compiled HogQL that selects the offending+ rows — re-run that query to investigate a failure.+ feature_flag: data-quality-checks+ data-quality-check-run-on-table:+ operation: warehouse_tables_checks_run_create+ enabled: true+ scopes:+ - warehouse_table:write+ - query:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Run a data quality check on a table+ description: >+ Run one check now. Returns a suite run to poll; read the outcome from+ system.information_schema.data_quality_check_runs once it finishes.+ feature_flag: data-quality-checks+ data-quality-check-run-on-view:+ operation: warehouse_saved_queries_checks_run_create+ enabled: true+ scopes:+ - warehouse_view:write+ - query:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Run a data quality check on a view+ description: >+ Run one check now. Returns a suite run to poll; read the outcome from+ system.information_schema.data_quality_check_runs once it finishes.+ feature_flag: data-quality-checks+ data-quality-check-types:+ operation: warehouse_saved_queries_checks_check_types_list+ enabled: true+ scopes:+ - warehouse_view:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List data quality check types+ description: >+ The check types this project can author, each with the JSON schema its config is validated against. Static+ catalog — the saved_query_id path parameter can be any view's id.+ feature_flag: data-quality-checks+ data-quality-check-update-on-table:+ operation: warehouse_tables_checks_partial_update+ enabled: true+ scopes:+ - warehouse_table:write+ - query:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Update a data quality check on a table+ description: >+ Change a check's presentation (name, description, severity, enabled, tags). The assertion itself —+ check_type, column_name, config — is immutable; create a new check and delete this one instead.+ feature_flag: data-quality-checks+ data-quality-check-update-on-view:+ operation: warehouse_saved_queries_checks_partial_update+ enabled: true+ scopes:+ - warehouse_view:write+ - query:read+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Update a data quality check on a view+ description: >+ Change a check's presentation (name, description, severity, enabled, tags). The assertion itself —+ check_type, column_name, config — is immutable; create a new check and delete this one instead.+ feature_flag: data-quality-checks+ warehouse-saved-queries-check-suite-runs-check-runs-list:+ operation: warehouse_saved_queries_check_suite_runs_check_runs_list+ enabled: false+ warehouse-saved-queries-check-suite-runs-list:+ operation: warehouse_saved_queries_check_suite_runs_list+ enabled: false+ warehouse-saved-queries-check-suite-runs-retrieve:+ operation: warehouse_saved_queries_check_suite_runs_retrieve+ enabled: false+ warehouse-saved-queries-checks-health-retrieve:+ operation: warehouse_saved_queries_checks_health_retrieve+ enabled: false+ warehouse-saved-queries-checks-list:+ operation: warehouse_saved_queries_checks_list+ enabled: false+ warehouse-saved-queries-checks-retrieve:+ operation: warehouse_saved_queries_checks_retrieve+ enabled: false+ warehouse-saved-queries-checks-run-all-create:+ operation: warehouse_saved_queries_checks_run_all_create+ enabled: false+ warehouse-saved-queries-checks-update:+ operation: warehouse_saved_queries_checks_update+ enabled: false+ warehouse-tables-check-suite-runs-check-runs-list:+ operation: warehouse_tables_check_suite_runs_check_runs_list+ enabled: false+ warehouse-tables-check-suite-runs-list:+ operation: warehouse_tables_check_suite_runs_list+ enabled: false+ warehouse-tables-check-suite-runs-retrieve:+ operation: warehouse_tables_check_suite_runs_retrieve+ enabled: false+ warehouse-tables-checks-check-types-list:+ operation: warehouse_tables_checks_check_types_list+ enabled: false+ warehouse-tables-checks-health-retrieve:+ operation: warehouse_tables_checks_health_retrieve+ enabled: false+ warehouse-tables-checks-list:+ operation: warehouse_tables_checks_list+ enabled: false+ warehouse-tables-checks-retrieve:+ operation: warehouse_tables_checks_retrieve+ enabled: false+ warehouse-tables-checks-run-all-create:+ operation: warehouse_tables_checks_run_all_create+ enabled: false+ warehouse-tables-checks-update:+ operation: warehouse_tables_checks_update+ enabled: falsediff --git a/products/data_quality/skills/authoring-data-quality-checks/SKILL.md b/products/data_quality/skills/authoring-data-quality-checks/SKILL.mdnew file mode 100644index 000000000000..87fcc058a4a1--- /dev/null+++ b/products/data_quality/skills/authoring-data-quality-checks/SKILL.md@@ -0,0 +1,128 @@+---+name: authoring-data-quality-checks+description: >+ Adds and runs data quality checks (dbt-test style assertions) on a project's warehouse tables and+ saved-query views: not-null, uniqueness, accepted values, referential integrity, row-count bounds,+ freshness, and custom HogQL. Use when asked to test a model, validate a view, check for nulls or+ duplicates, add data quality checks, find out why a number looks wrong, or judge whether a warehouse+ table is trustworthy before using it in an analysis. To describe what data *means* (metrics,+ certifications, joins), see setting-up-data-catalog instead. Trigger terms: data quality, data test,+ dbt test, not null check, uniqueness check, freshness check, referential integrity, row count check,+ validate model, is this table trustworthy.+---++# Authoring data quality checks++A check is one assertion about one warehouse table or view. It compiles to a count-only HogQL query+and **passes when it finds zero failing rows** — the same semantics as `dbt test`. Failing rows are+never stored; only counts and the compiled query are, so to see the offending rows you re-run the+stored query yourself.++`row_count` is the exception. It passes when the observed count is within its configured min/max+bounds, so its `failed_row_count` comes back null and its stored query returns that single count,+not offending rows. Read the observed count to judge it rather than looking for matched rows.++Reads go through SQL (`system.information_schema.data_quality_*`); writes and runs go through the+data-quality MCP tools.++## Before you write anything: look++Two queries save you from the two most common mistakes — duplicating a check, and checking a column+that doesn't exist.++```sql+-- What is already covered?+SELECT name, subject_name, column_name, check_type, config, severity, last_status+FROM system.information_schema.data_quality_checks+WHERE subject_name = 'orders'++-- What columns are there, and what do they mean?+SELECT column_name, data_type, description+FROM system.information_schema.columns+WHERE table_name = 'orders'+```++Re-creating a byte-identical check is a harmless no-op — checks are keyed by a fingerprint of the+subject, type, column, and config, so an identical create upserts. A _near_-duplicate is not+harmless: it doubles the noise for whoever reads the results. If an existing check's assertion is+close but wrong, create the corrected check and delete the old one — the assertion (type, column,+config) is immutable and the subject is fixed by the URL, so an update that tries to change them is+rejected. Update is only for metadata, severity, and ownership.++## Choosing checks++Aim for a handful that would actually catch a real regression, not blanket coverage. A model with+twenty checks nobody reads is worse than three that fail meaningfully.++Reach for these first, in roughly this order:++- **`not_null` on the columns downstream joins and filters depend on.** The single highest-value+ check. A null join key silently drops rows.+- **`unique` on whatever the model claims is its grain.** If `orders` is one row per order, say so.+- **`relationships` on foreign keys.** Catches the join that quietly stopped matching after an+ upstream change.+- **`accepted_values` on status and category columns** whose downstream logic branches on them.+- **`freshness` on the timestamp column of anything that syncs.** Catches a dead pipeline, which no+ row-level check will.+- **`row_count` bounds** when you know the plausible range. Good for catching a truncated sync.+- **`custom_sql`** only when nothing above expresses the invariant — e.g. cross-column arithmetic+ (`select 1 from orders where total != subtotal + tax`). Every row it returns counts as a failure.++Call `posthog:data-quality-check-types` for each type's exact config schema rather than guessing.++Checks live on the subject they audit: create them with `data-quality-check-create-on-view`+(`saved_query_id` path parameter) or `data-quality-check-create-on-table` (`table_id`).++## Severity and triggers++**Severity** is a decision about consequences, not about confidence. Use `error` when the failure+means downstream numbers should not be trusted — those failures mark the subject `failing` and+notify. Use `warn` for things worth surfacing that nobody would act on today. When unsure, `warn` is+the safer default: an `error` check that cries wolf gets everything ignored.++**Triggers** — there is nothing to schedule. A check runs when its subject's data changes: a+materialized view's checks run as part of its refresh (and, when the team turns the gate on, a+refresh whose error-severity checks fail is not published), a source table's checks run after each+completed sync, and a plain view's checks run when its DAG runs. Checks on a view outside any DAG+only run on demand.++## Verify what you wrote++Author, run once, read the result. A check nobody has run is a guess.++1. `posthog:data-quality-check-create-on-view` (or `-on-table`)+2. `posthog:data-quality-check-run-on-view` (or `-on-table`) — returns a suite run+3. Poll `system.information_schema.data_quality_check_runs` (or+ `posthog:data-quality-check-results-on-view`/`-on-table`) for the outcome++A `failed` result on the first run is the interesting case: either you found real bad data, or the+assertion is wrong. Take the `compiled_query` off the run, execute it with `posthog:execute-sql`, and+look at what it actually matched before reporting anything. That `compiled_query` comes from+`posthog:data-quality-check-results-on-view`/`-on-table`; the information_schema poll in step 3 does+not return it. An `errored` result is never a data+problem — the query could not run at all, usually a column name typo or a subject that no longer+exists.++## Judging a source before you use it++When an analysis depends on a warehouse table or view, check its verdict first:++```sql+SELECT subject_name, health, checks_total, checks_failing, last_run_at+FROM system.information_schema.data_quality_health+```++- `failing` — an error-severity check found bad data. Say so in your answer; don't quietly use it.+- `erroring` — a check couldn't run. The data may be fine, but nobody is watching it.+- `warn` — only warn-severity failures. Usable, worth a mention.+- `healthy` — checks ran and passed.+- `unknown` / absent — no checks, or none have run. Absence of failures is not evidence of health.++For the history behind a verdict, `system.information_schema.data_quality_check_runs` carries recent+executions with `observed_value` recorded on passes too, so you can see when a number started+drifting rather than just that it is wrong now.++## Related++- `setting-up-data-catalog` — what the data _means_: metrics, trust marks, relationships.+- `querying-posthog-data` — the schema-discovery and HogQL rules these queries follow.diff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.pyindex a7f58850469d..066ffba2ed79 100644--- a/products/notifications/backend/facade/enums.py+++ b/products/notifications/backend/facade/enums.py@@ -21,6 +21,7 @@ class NotificationType(str, Enum):SUBSCRIPTION_NUDGE = "subscription_nudge"EMAIL_REPUTATION = "email_reputation"MATERIALIZATION_FAILURE = "materialization_failure"+ DATA_QUALITY_CHECK_FAILURE = "data_quality_check_failure"class Priority(str, Enum):diff --git a/products/notifications/backend/migrations/0024_alter_notificationevent_notification_type.py b/products/notifications/backend/migrations/0024_alter_notificationevent_notification_type.pynew file mode 100644index 000000000000..4139eeabd7c5--- /dev/null+++ b/products/notifications/backend/migrations/0024_alter_notificationevent_notification_type.py@@ -0,0 +1,35 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notifications", "0023_add_notification_idempotency_key_index"),+ ]++ operations = [+ migrations.AlterField(+ model_name="notificationevent",+ name="notification_type",+ field=models.CharField(+ choices=[+ ("comment_mention", "COMMENT_MENTION"),+ ("alert_firing", "ALERT_FIRING"),+ ("issue_assigned", "ISSUE_ASSIGNED"),+ ("approval_requested", "APPROVAL_REQUESTED"),+ ("approval_resolved", "APPROVAL_RESOLVED"),+ ("experiment_concluded", "EXPERIMENT_CONCLUDED"),+ ("pipeline_failure", "PIPELINE_FAILURE"),+ ("project_created", "PROJECT_CREATED"),+ ("usage_spike", "USAGE_SPIKE"),+ ("reminder", "REMINDER"),+ ("web_analytics_digest", "WEB_ANALYTICS_DIGEST"),+ ("achievement_unlocked", "ACHIEVEMENT_UNLOCKED"),+ ("subscription_nudge", "SUBSCRIPTION_NUDGE"),+ ("email_reputation", "EMAIL_REPUTATION"),+ ("materialization_failure", "MATERIALIZATION_FAILURE"),+ ("data_quality_check_failure", "DATA_QUALITY_CHECK_FAILURE"),+ ],+ max_length=32,+ ),+ ),+ ]diff --git a/products/notifications/backend/migrations/max_migration.txt b/products/notifications/backend/migrations/max_migration.txtindex e37adfd027e7..c6e0236aea7b 100644--- a/products/notifications/backend/migrations/max_migration.txt+++ b/products/notifications/backend/migrations/max_migration.txt@@ -1 +1 @@-0023_add_notification_idempotency_key_index+0024_alter_notificationevent_notification_typediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 82bae275018a..0123e36399e9 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -2536,6 +2536,171 @@},"feature_flag": "product-data-catalog"},+ "data-quality-check-create-on-table": {+ "description": "Add a dbt-test-style assertion to a synced warehouse table; the table's id is the table_id\npath parameter. A check passes when it finds zero failing rows.\n\nQuery `system.information_schema.data_quality_checks` first — re-creating an identical check is a no-op,\nbut a near-duplicate with different config is noise for whoever reviews the results.\n\nPrefer a generic type over custom_sql. Config per type:\n - not_null, unique: no config; set column_name.\n - accepted_values: {\"values\": [\"paid\", \"refunded\"]}; set column_name.\n - relationships: {\"to_subject_type\": \"table\", \"to_subject_uuid\": \"<uuid>\", \"to_column\": \"id\"}; set\n column_name.\n - row_count: {\"min\": 1} and/or {\"max\": 1000000}; no column_name.\n - freshness: {\"max_age_minutes\": 60}; set column_name to a timestamp column.\n - custom_sql: {\"query\": \"select 1 from orders where total < 0\"}; every row it returns is a failure.\n\nUse severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but\nnot acting on. Checks run automatically after each sync of the table; there is nothing to schedule.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Create a data quality check on a table",+ "title": "Create a data quality check on a table",+ "required_scopes": ["warehouse_table:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-create-on-view": {+ "description": "Add a dbt-test-style assertion to a saved query (view or materialized view); the view's id is\nthe saved_query_id path parameter. A check passes when it finds zero failing rows.\n\nQuery `system.information_schema.data_quality_checks` first — re-creating an identical check is a no-op,\nbut a near-duplicate with different config is noise for whoever reviews the results.\n\nPrefer a generic type over custom_sql. Config per type:\n - not_null, unique: no config; set column_name.\n - accepted_values: {\"values\": [\"paid\", \"refunded\"]}; set column_name.\n - relationships: {\"to_subject_type\": \"table\", \"to_subject_uuid\": \"<uuid>\", \"to_column\": \"id\"}; set\n column_name.\n - row_count: {\"min\": 1} and/or {\"max\": 1000000}; no column_name.\n - freshness: {\"max_age_minutes\": 60}; set column_name to a timestamp column.\n - custom_sql: {\"query\": \"select 1 from orders where total < 0\"}; every row it returns is a failure.\n\nUse severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but\nnot acting on. Checks run automatically when the view refreshes; there is nothing to schedule.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Create a data quality check on a view",+ "title": "Create a data quality check on a view",+ "required_scopes": ["warehouse_view:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-delete-on-table": {+ "description": "Delete a check. The API soft-deletes it, so its run history stays queryable in system.information_schema.data_quality_check_runs and past failures can still be dated.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Delete a data quality check on a table",+ "title": "Delete a data quality check on a table",+ "required_scopes": ["warehouse_table:write", "query:read"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-delete-on-view": {+ "description": "Delete a check. The API soft-deletes it, so its run history stays queryable in system.information_schema.data_quality_check_runs and past failures can still be dated.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Delete a data quality check on a view",+ "title": "Delete a data quality check on a view",+ "required_scopes": ["warehouse_view:write", "query:read"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-results-on-table": {+ "description": "The check's newest runs, including the failing-row count and the compiled HogQL that selects the offending rows — re-run that query to investigate a failure.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Recent results of a data quality check on a table",+ "title": "Recent results of a data quality check on a table",+ "required_scopes": ["warehouse_table:read", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-results-on-view": {+ "description": "The check's newest runs, including the failing-row count and the compiled HogQL that selects the offending rows — re-run that query to investigate a failure.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Recent results of a data quality check on a view",+ "title": "Recent results of a data quality check on a view",+ "required_scopes": ["warehouse_view:read", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-run-on-table": {+ "description": "Run one check now. Returns a suite run to poll; read the outcome from system.information_schema.data_quality_check_runs once it finishes.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Run a data quality check on a table",+ "title": "Run a data quality check on a table",+ "required_scopes": ["warehouse_table:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-run-on-view": {+ "description": "Run one check now. Returns a suite run to poll; read the outcome from system.information_schema.data_quality_check_runs once it finishes.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Run a data quality check on a view",+ "title": "Run a data quality check on a view",+ "required_scopes": ["warehouse_view:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-types": {+ "description": "The check types this project can author, each with the JSON schema its config is validated against. Static catalog — the saved_query_id path parameter can be any view's id.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "List data quality check types",+ "title": "List data quality check types",+ "required_scopes": ["warehouse_view:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-update-on-table": {+ "description": "Change a check's presentation (name, description, severity, enabled, tags). The assertion itself — check_type, column_name, config — is immutable; create a new check and delete this one instead.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Update a data quality check on a table",+ "title": "Update a data quality check on a table",+ "required_scopes": ["warehouse_table:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-update-on-view": {+ "description": "Change a check's presentation (name, description, severity, enabled, tags). The assertion itself — check_type, column_name, config — is immutable; create a new check and delete this one instead.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Update a data quality check on a view",+ "title": "Update a data quality check on a view",+ "required_scopes": ["warehouse_view:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },"data-warehouse-source-connect-link": {"description": "Return a secure browser link to connect a data warehouse source WITHOUT the user pasting secrets into the chat. The link opens a minimal page rendering the source's full connection form — the user authorizes via OAuth or enters credentials there, whichever the source offers — and the page stores the connection details encrypted and temporarily; it does NOT create the source. This is the preferred, secure way to collect credentials: share the returned connect_url with the user, wait for them to confirm they're done, then find the stored credential via 'data-warehouse-stored-credentials-list' (filter by source_type, newest first) and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use, expire after 24 hours, and are only visible to the PostHog user who entered them — the page must be filled by the same user this session authenticates as. Never ask the user to paste raw database passwords, API keys, or OAuth tokens into the chat.","category": "Warehouse sources",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex f9f1611d48fb..8444b4bb75b3 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -2551,6 +2551,171 @@},"feature_flag": "product-data-catalog"},+ "data-quality-check-create-on-table": {+ "description": "Add a dbt-test-style assertion to a synced warehouse table; the table's id is the table_id\npath parameter. A check passes when it finds zero failing rows.\n\nQuery `system.information_schema.data_quality_checks` first — re-creating an identical check is a no-op,\nbut a near-duplicate with different config is noise for whoever reviews the results.\n\nPrefer a generic type over custom_sql. Config per type:\n - not_null, unique: no config; set column_name.\n - accepted_values: {\"values\": [\"paid\", \"refunded\"]}; set column_name.\n - relationships: {\"to_subject_type\": \"table\", \"to_subject_uuid\": \"<uuid>\", \"to_column\": \"id\"}; set\n column_name.\n - row_count: {\"min\": 1} and/or {\"max\": 1000000}; no column_name.\n - freshness: {\"max_age_minutes\": 60}; set column_name to a timestamp column.\n - custom_sql: {\"query\": \"select 1 from orders where total < 0\"}; every row it returns is a failure.\n\nUse severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but\nnot acting on. Checks run automatically after each sync of the table; there is nothing to schedule.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Create a data quality check on a table",+ "title": "Create a data quality check on a table",+ "required_scopes": ["warehouse_table:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-create-on-view": {+ "description": "Add a dbt-test-style assertion to a saved query (view or materialized view); the view's id is\nthe saved_query_id path parameter. A check passes when it finds zero failing rows.\n\nQuery `system.information_schema.data_quality_checks` first — re-creating an identical check is a no-op,\nbut a near-duplicate with different config is noise for whoever reviews the results.\n\nPrefer a generic type over custom_sql. Config per type:\n - not_null, unique: no config; set column_name.\n - accepted_values: {\"values\": [\"paid\", \"refunded\"]}; set column_name.\n - relationships: {\"to_subject_type\": \"table\", \"to_subject_uuid\": \"<uuid>\", \"to_column\": \"id\"}; set\n column_name.\n - row_count: {\"min\": 1} and/or {\"max\": 1000000}; no column_name.\n - freshness: {\"max_age_minutes\": 60}; set column_name to a timestamp column.\n - custom_sql: {\"query\": \"select 1 from orders where total < 0\"}; every row it returns is a failure.\n\nUse severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but\nnot acting on. Checks run automatically when the view refreshes; there is nothing to schedule.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Create a data quality check on a view",+ "title": "Create a data quality check on a view",+ "required_scopes": ["warehouse_view:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-delete-on-table": {+ "description": "Delete a check. The API soft-deletes it, so its run history stays queryable in system.information_schema.data_quality_check_runs and past failures can still be dated.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Delete a data quality check on a table",+ "title": "Delete a data quality check on a table",+ "required_scopes": ["warehouse_table:write", "query:read"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-delete-on-view": {+ "description": "Delete a check. The API soft-deletes it, so its run history stays queryable in system.information_schema.data_quality_check_runs and past failures can still be dated.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Delete a data quality check on a view",+ "title": "Delete a data quality check on a view",+ "required_scopes": ["warehouse_view:write", "query:read"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-results-on-table": {+ "description": "The check's newest runs, including the failing-row count and the compiled HogQL that selects the offending rows — re-run that query to investigate a failure.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Recent results of a data quality check on a table",+ "title": "Recent results of a data quality check on a table",+ "required_scopes": ["warehouse_table:read", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-results-on-view": {+ "description": "The check's newest runs, including the failing-row count and the compiled HogQL that selects the offending rows — re-run that query to investigate a failure.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Recent results of a data quality check on a view",+ "title": "Recent results of a data quality check on a view",+ "required_scopes": ["warehouse_view:read", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-run-on-table": {+ "description": "Run one check now. Returns a suite run to poll; read the outcome from system.information_schema.data_quality_check_runs once it finishes.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Run a data quality check on a table",+ "title": "Run a data quality check on a table",+ "required_scopes": ["warehouse_table:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-run-on-view": {+ "description": "Run one check now. Returns a suite run to poll; read the outcome from system.information_schema.data_quality_check_runs once it finishes.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Run a data quality check on a view",+ "title": "Run a data quality check on a view",+ "required_scopes": ["warehouse_view:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-types": {+ "description": "The check types this project can author, each with the JSON schema its config is validated against. Static catalog — the saved_query_id path parameter can be any view's id.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "List data quality check types",+ "title": "List data quality check types",+ "required_scopes": ["warehouse_view:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-update-on-table": {+ "description": "Change a check's presentation (name, description, severity, enabled, tags). The assertion itself — check_type, column_name, config — is immutable; create a new check and delete this one instead.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Update a data quality check on a table",+ "title": "Update a data quality check on a table",+ "required_scopes": ["warehouse_table:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },+ "data-quality-check-update-on-view": {+ "description": "Change a check's presentation (name, description, severity, enabled, tags). The assertion itself — check_type, column_name, config — is immutable; create a new check and delete this one instead.",+ "category": "Data quality",+ "feature": "data_quality",+ "summary": "Update a data quality check on a view",+ "title": "Update a data quality check on a view",+ "required_scopes": ["warehouse_view:write", "query:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "data-quality-checks"+ },"data-warehouse-source-connect-link": {"description": "Return a secure browser link to connect a data warehouse source WITHOUT the user pasting secrets into the chat. The link opens a minimal page rendering the source's full connection form — the user authorizes via OAuth or enters credentials there, whichever the source offers — and the page stores the connection details encrypted and temporarily; it does NOT create the source. This is the preferred, secure way to collect credentials: share the returned connect_url with the user, wait for them to confirm they're done, then find the stored credential via 'data-warehouse-stored-credentials-list' (filter by source_type, newest first) and call 'data-warehouse-source-setup' with {'credential_id': '<uuid>'} in the payload. Stored credentials are single-use, expire after 24 hours, and are only visible to the PostHog user who entered them — the page must be filled by the same user this session authenticates as. Never ask the user to paste raw database passwords, API keys, or OAuth tokens into the chat.","category": "Warehouse sources",diff --git a/services/mcp/src/generated/data_quality/api.ts b/services/mcp/src/generated/data_quality/api.tsindex e2fb99ac0809..99dd40e471bd 100644--- a/services/mcp/src/generated/data_quality/api.ts+++ b/services/mcp/src/generated/data_quality/api.ts@@ -3,314 +3,417 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 10 enabled ops+ * PostHog API - MCP 11 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'/**- * Read-only reports for batches of check executions.+ * 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 DataQualityCheckSuiteRunsRetrieveParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this data quality suite run.'),+export const WarehouseSavedQueriesChecksCreateParams = /* @__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\/."),+ saved_query_id: zod.string(),})-/**- * 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\/."- ),-})+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.')/**- * 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.+ * CRUD for one subject's checks, plus the actions that run them and report on them.*/-export const DataQualityChecksCreateParams = /* @__PURE__ */ zod.object({+export const WarehouseSavedQueriesChecksPartialUpdateParams = /* @__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\/."),+ saved_query_id: zod.string(),})-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 warehouseSavedQueriesChecksPartialUpdateBodyNameMax = 128-export const dataQualityChecksCreateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const dataQualityChecksCreateBodyColumnNameMax = 400+export const warehouseSavedQueriesChecksPartialUpdateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const warehouseSavedQueriesChecksPartialUpdateBodyColumnNameMax = 400-export const dataQualityChecksCreateBodyScheduleIntervalMinutesMin = -2147483648-export const dataQualityChecksCreateBodyScheduleIntervalMinutesMax = 2147483647+export const warehouseSavedQueriesChecksPartialUpdateBodyAiModelMax = 128-export const dataQualityChecksCreateBodyAiModelMax = 128+export const warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMin = 0+export const warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMax = 1-export const dataQualityChecksCreateBodyConfidenceMin = 0-export const dataQualityChecksCreateBodyConfidenceMax = 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.')-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+/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const WarehouseSavedQueriesChecksDestroyParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this data quality check.'),+ project_id: 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"+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."),- 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."),+ saved_query_id: zod.string(),})/**- * CRUD for data quality checks, plus the actions that run them and report on them.+ * Run this check now. Returns the suite run to poll for the report.*/-export const DataQualityChecksPartialUpdateParams = /* @__PURE__ */ zod.object({+export const WarehouseSavedQueriesChecksRunCreateParams = /* @__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\/."),+ saved_query_id: zod.string(),})-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+/**+ * Recent run history for this check, newest first.+ */+export const WarehouseSavedQueriesChecksRunsListParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this data quality check.'),+ project_id: 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"+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."),- 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."),+ saved_query_id: zod.string(),})/**- * CRUD for data quality checks, plus the actions that run them and report on them.+ * The check types this project can author, with the JSON schema of each type's config.*/-export const DataQualityChecksDestroyParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this data quality check.'),+export const WarehouseSavedQueriesChecksCheckTypesListParams = /* @__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\/."),+ saved_query_id: zod.string(),})/**- * Run this check now. Returns the suite run to poll for the report.+ * 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 DataQualityChecksRunCreateParams = /* @__PURE__ */ zod.object({- id: zod.string().describe('A UUID string identifying this data quality check.'),+export const WarehouseTablesChecksCreateParams = /* @__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\/."),+ table_id: zod.string(),})+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.')+/**- * Recent run history for this check, newest first.+ * CRUD for one subject's checks, plus the actions that run them and report on them.*/-export const DataQualityChecksRunsListParams = /* @__PURE__ */ zod.object({+export const WarehouseTablesChecksPartialUpdateParams = /* @__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\/."),+ table_id: zod.string(),})+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.')+/**- * The check types this project can author, with the JSON schema of each type's config.+ * CRUD for one subject's checks, plus the actions that run them and report on them.*/-export const DataQualityChecksCheckTypesListParams = /* @__PURE__ */ zod.object({+export const WarehouseTablesChecksDestroyParams = /* @__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\/."),+ table_id: zod.string(),})/**- * Health rollup for one table or view, from the denormalized status of its checks.+ * Run this check now. Returns the suite run to poll for the report.*/-export const DataQualityChecksHealthRetrieveParams = /* @__PURE__ */ zod.object({+export const WarehouseTablesChecksRunCreateParams = /* @__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 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.'),+ table_id: zod.string(),})/**- * Run every enabled check on a table or view. Returns the suite run to poll for the report.+ * Recent run history for this check, newest first.*/-export const DataQualityChecksRunForSubjectCreateParams = /* @__PURE__ */ zod.object({+export const WarehouseTablesChecksRunsListParams = /* @__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 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.'),+ table_id: zod.string(),})diff --git a/services/mcp/src/tools/generated/data_quality.ts b/services/mcp/src/tools/generated/data_quality.tsnew file mode 100644index 000000000000..0c4affcce166--- /dev/null+++ b/services/mcp/src/tools/generated/data_quality.ts@@ -0,0 +1,387 @@+// AUTO-GENERATED from products/data_quality/mcp/tools.yaml + OpenAPI — do not edit+import { z } from 'zod'++import type { Schemas } from '@/api/generated'+import {+ WarehouseSavedQueriesChecksCheckTypesListParams,+ WarehouseSavedQueriesChecksCreateBody,+ WarehouseSavedQueriesChecksCreateParams,+ WarehouseSavedQueriesChecksDestroyParams,+ WarehouseSavedQueriesChecksPartialUpdateBody,+ WarehouseSavedQueriesChecksPartialUpdateParams,+ WarehouseSavedQueriesChecksRunCreateParams,+ WarehouseSavedQueriesChecksRunsListParams,+ WarehouseTablesChecksCreateBody,+ WarehouseTablesChecksCreateParams,+ WarehouseTablesChecksDestroyParams,+ WarehouseTablesChecksPartialUpdateBody,+ WarehouseTablesChecksPartialUpdateParams,+ WarehouseTablesChecksRunCreateParams,+ WarehouseTablesChecksRunsListParams,+} from '@/generated/data_quality/api'+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'++const DataQualityCheckCreateOnTableSchema = WarehouseTablesChecksCreateParams.omit({ project_id: true }).extend(+ WarehouseTablesChecksCreateBody.shape+)++const dataQualityCheckCreateOnTable = (): ToolBase<+ typeof DataQualityCheckCreateOnTableSchema,+ Schemas.DataQualityCheck+> => ({+ name: 'data-quality-check-create-on-table',+ schema: DataQualityCheckCreateOnTableSchema,+ handler: async (context: Context, params: z.infer<typeof DataQualityCheckCreateOnTableSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ if (params.column_name !== undefined) {+ body['column_name'] = params.column_name+ }+ if (params.check_type !== undefined) {+ body['check_type'] = params.check_type+ }+ if (params.config !== undefined) {+ body['config'] = params.config+ }+ if (params.severity !== undefined) {+ body['severity'] = params.severity+ }+ if (params.enabled !== undefined) {+ body['enabled'] = params.enabled+ }+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }+ if (params.created_source !== undefined) {+ body['created_source'] = params.created_source+ }+ if (params.ai_model !== undefined) {+ body['ai_model'] = params.ai_model+ }+ if (params.confidence !== undefined) {+ body['confidence'] = params.confidence+ }+ if (params.reasoning !== undefined) {+ body['reasoning'] = params.reasoning+ }+ body['created_source'] = 'ai_generated'+ const result = await context.api.request<Schemas.DataQualityCheck>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_tables/${encodeURIComponent(String(params.table_id))}/checks/`,+ body,+ })+ return result+ },+})++const DataQualityCheckCreateOnViewSchema = WarehouseSavedQueriesChecksCreateParams.omit({ project_id: true }).extend(+ WarehouseSavedQueriesChecksCreateBody.shape+)++const dataQualityCheckCreateOnView = (): ToolBase<+ typeof DataQualityCheckCreateOnViewSchema,+ Schemas.DataQualityCheck+> => ({+ name: 'data-quality-check-create-on-view',+ schema: DataQualityCheckCreateOnViewSchema,+ handler: async (context: Context, params: z.infer<typeof DataQualityCheckCreateOnViewSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ if (params.column_name !== undefined) {+ body['column_name'] = params.column_name+ }+ if (params.check_type !== undefined) {+ body['check_type'] = params.check_type+ }+ if (params.config !== undefined) {+ body['config'] = params.config+ }+ if (params.severity !== undefined) {+ body['severity'] = params.severity+ }+ if (params.enabled !== undefined) {+ body['enabled'] = params.enabled+ }+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }+ if (params.created_source !== undefined) {+ body['created_source'] = params.created_source+ }+ if (params.ai_model !== undefined) {+ body['ai_model'] = params.ai_model+ }+ if (params.confidence !== undefined) {+ body['confidence'] = params.confidence+ }+ if (params.reasoning !== undefined) {+ body['reasoning'] = params.reasoning+ }+ body['created_source'] = 'ai_generated'+ const result = await context.api.request<Schemas.DataQualityCheck>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.saved_query_id))}/checks/`,+ body,+ })+ return result+ },+})++const DataQualityCheckDeleteOnTableSchema = WarehouseTablesChecksDestroyParams.omit({ project_id: true })++const dataQualityCheckDeleteOnTable = (): ToolBase<typeof DataQualityCheckDeleteOnTableSchema, unknown> => ({+ name: 'data-quality-check-delete-on-table',+ schema: DataQualityCheckDeleteOnTableSchema,+ handler: async (context: Context, params: z.infer<typeof DataQualityCheckDeleteOnTableSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<unknown>({+ method: 'DELETE',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_tables/${encodeURIComponent(String(params.table_id))}/checks/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})++const DataQualityCheckDeleteOnViewSchema = WarehouseSavedQueriesChecksDestroyParams.omit({ project_id: true })++const dataQualityCheckDeleteOnView = (): ToolBase<typeof DataQualityCheckDeleteOnViewSchema, unknown> => ({+ name: 'data-quality-check-delete-on-view',+ schema: DataQualityCheckDeleteOnViewSchema,+ handler: async (context: Context, params: z.infer<typeof DataQualityCheckDeleteOnViewSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<unknown>({+ method: 'DELETE',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.saved_query_id))}/checks/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})++const DataQualityCheckResultsOnTableSchema = WarehouseTablesChecksRunsListParams.omit({ project_id: true })++const dataQualityCheckResultsOnTable = (): ToolBase<+ typeof DataQualityCheckResultsOnTableSchema,+ Schemas.DataQualityCheckRun[]+> => ({+ name: 'data-quality-check-results-on-table',+ schema: DataQualityCheckResultsOnTableSchema,+ handler: async (context: Context, params: z.infer<typeof DataQualityCheckResultsOnTableSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.DataQualityCheckRun[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_tables/${encodeURIComponent(String(params.table_id))}/checks/${encodeURIComponent(String(params.id))}/runs/`,+ })+ return result+ },+})++const DataQualityCheckResultsOnViewSchema = WarehouseSavedQueriesChecksRunsListParams.omit({ project_id: true })++const dataQualityCheckResultsOnView = (): ToolBase<+ typeof DataQualityCheckResultsOnViewSchema,+ Schemas.DataQualityCheckRun[]+> => ({+ name: 'data-quality-check-results-on-view',+ schema: DataQualityCheckResultsOnViewSchema,+ handler: async (context: Context, params: z.infer<typeof DataQualityCheckResultsOnViewSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.DataQualityCheckRun[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.saved_query_id))}/checks/${encodeURIComponent(String(params.id))}/runs/`,+ })+ return result+ },+})++const DataQualityCheckRunOnTableSchema = WarehouseTablesChecksRunCreateParams.omit({ project_id: true })++const dataQualityCheckRunOnTable = (): ToolBase<+ typeof DataQualityCheckRunOnTableSchema,+ Schemas.DataQualitySuiteRun+> => ({+ name: 'data-quality-check-run-on-table',+ schema: DataQualityCheckRunOnTableSchema,+ handler: async (context: Context, params: z.infer<typeof DataQualityCheckRunOnTableSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.DataQualitySuiteRun>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_tables/${encodeURIComponent(String(params.table_id))}/checks/${encodeURIComponent(String(params.id))}/run/`,+ })+ return result+ },+})++const DataQualityCheckRunOnViewSchema = WarehouseSavedQueriesChecksRunCreateParams.omit({ project_id: true })++const dataQualityCheckRunOnView = (): ToolBase<+ typeof DataQualityCheckRunOnViewSchema,+ Schemas.DataQualitySuiteRun+> => ({+ name: 'data-quality-check-run-on-view',+ schema: DataQualityCheckRunOnViewSchema,+ handler: async (context: Context, params: z.infer<typeof DataQualityCheckRunOnViewSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.DataQualitySuiteRun>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.saved_query_id))}/checks/${encodeURIComponent(String(params.id))}/run/`,+ })+ return result+ },+})++const DataQualityCheckTypesSchema = WarehouseSavedQueriesChecksCheckTypesListParams.omit({ project_id: true })++const dataQualityCheckTypes = (): ToolBase<typeof DataQualityCheckTypesSchema, Schemas.DataQualityCheckType[]> => ({+ name: 'data-quality-check-types',+ schema: DataQualityCheckTypesSchema,+ handler: async (context: Context, params: z.infer<typeof DataQualityCheckTypesSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.DataQualityCheckType[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.saved_query_id))}/checks/check_types/`,+ })+ return result+ },+})++const DataQualityCheckUpdateOnTableSchema = WarehouseTablesChecksPartialUpdateParams.omit({ project_id: true }).extend(+ WarehouseTablesChecksPartialUpdateBody.shape+)++const dataQualityCheckUpdateOnTable = (): ToolBase<+ typeof DataQualityCheckUpdateOnTableSchema,+ Schemas.DataQualityCheck+> => ({+ name: 'data-quality-check-update-on-table',+ schema: DataQualityCheckUpdateOnTableSchema,+ handler: async (context: Context, params: z.infer<typeof DataQualityCheckUpdateOnTableSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ if (params.column_name !== undefined) {+ body['column_name'] = params.column_name+ }+ if (params.check_type !== undefined) {+ body['check_type'] = params.check_type+ }+ if (params.config !== undefined) {+ body['config'] = params.config+ }+ if (params.severity !== undefined) {+ body['severity'] = params.severity+ }+ if (params.enabled !== undefined) {+ body['enabled'] = params.enabled+ }+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }+ if (params.created_source !== undefined) {+ body['created_source'] = params.created_source+ }+ if (params.ai_model !== undefined) {+ body['ai_model'] = params.ai_model+ }+ if (params.confidence !== undefined) {+ body['confidence'] = params.confidence+ }+ if (params.reasoning !== undefined) {+ body['reasoning'] = params.reasoning+ }+ const result = await context.api.request<Schemas.DataQualityCheck>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_tables/${encodeURIComponent(String(params.table_id))}/checks/${encodeURIComponent(String(params.id))}/`,+ body,+ })+ return result+ },+})++const DataQualityCheckUpdateOnViewSchema = WarehouseSavedQueriesChecksPartialUpdateParams.omit({+ project_id: true,+}).extend(WarehouseSavedQueriesChecksPartialUpdateBody.shape)++const dataQualityCheckUpdateOnView = (): ToolBase<+ typeof DataQualityCheckUpdateOnViewSchema,+ Schemas.DataQualityCheck+> => ({+ name: 'data-quality-check-update-on-view',+ schema: DataQualityCheckUpdateOnViewSchema,+ handler: async (context: Context, params: z.infer<typeof DataQualityCheckUpdateOnViewSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ if (params.column_name !== undefined) {+ body['column_name'] = params.column_name+ }+ if (params.check_type !== undefined) {+ body['check_type'] = params.check_type+ }+ if (params.config !== undefined) {+ body['config'] = params.config+ }+ if (params.severity !== undefined) {+ body['severity'] = params.severity+ }+ if (params.enabled !== undefined) {+ body['enabled'] = params.enabled+ }+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }+ if (params.created_source !== undefined) {+ body['created_source'] = params.created_source+ }+ if (params.ai_model !== undefined) {+ body['ai_model'] = params.ai_model+ }+ if (params.confidence !== undefined) {+ body['confidence'] = params.confidence+ }+ if (params.reasoning !== undefined) {+ body['reasoning'] = params.reasoning+ }+ const result = await context.api.request<Schemas.DataQualityCheck>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.saved_query_id))}/checks/${encodeURIComponent(String(params.id))}/`,+ body,+ })+ return result+ },+})++export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'data-quality-check-create-on-table': dataQualityCheckCreateOnTable,+ 'data-quality-check-create-on-view': dataQualityCheckCreateOnView,+ 'data-quality-check-delete-on-table': dataQualityCheckDeleteOnTable,+ 'data-quality-check-delete-on-view': dataQualityCheckDeleteOnView,+ 'data-quality-check-results-on-table': dataQualityCheckResultsOnTable,+ 'data-quality-check-results-on-view': dataQualityCheckResultsOnView,+ 'data-quality-check-run-on-table': dataQualityCheckRunOnTable,+ 'data-quality-check-run-on-view': dataQualityCheckRunOnView,+ 'data-quality-check-types': dataQualityCheckTypes,+ 'data-quality-check-update-on-table': dataQualityCheckUpdateOnTable,+ 'data-quality-check-update-on-view': dataQualityCheckUpdateOnView,+}diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.tsindex 81780fe29f1c..fd5faa339388 100644--- a/services/mcp/src/tools/generated/index.ts+++ b/services/mcp/src/tools/generated/index.ts@@ -17,6 +17,7 @@ import { GENERATED_TOOLS as core } from './core'import { GENERATED_TOOLS as customer_analytics } from './customer_analytics'import { GENERATED_TOOLS as dashboards } from './dashboards'import { GENERATED_TOOLS as data_catalog } from './data_catalog'+import { GENERATED_TOOLS as data_quality } from './data_quality'import { GENERATED_TOOLS as data_warehouse } from './data_warehouse'import { GENERATED_TOOLS as docs } from './docs'import { GENERATED_TOOLS as early_access_features } from './early_access_features'@@ -78,6 +79,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =...customer_analytics,...dashboards,...data_catalog,+ ...data_quality,...data_warehouse,...docs,...early_access_features,diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 1126091d25ab..589efc49f018 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -880,9 +880,10 @@ describe('Tool Filtering - Feature Flags', () => {'posthog-connect','experiment-behavior-comparison','data-warehouse-scene',+ 'data-quality-checks',]))- expect(flags).toHaveLength(30)+ expect(flags).toHaveLength(31)})it('every loops tool is gated on the loops flag', () => {diff --git a/tach.toml b/tach.tomlindex 3c990b67fc4c..0ff0e8cd6356 100644--- a/tach.toml+++ b/tach.toml@@ -1294,6 +1294,7 @@ path = "products.data_quality"depends_on = ["posthog","products.data_modeling",+ "products.notifications","products.warehouse_sources",]layer = "modules"