Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-quality): add the data_quality product with checks and their compiler (#74691)

Thiago Salvatore90dded19dc78
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 921f8f4f02ef..287c886087e6 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -197,6 +197,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"TeamConversationsTeamsChannelSync",
"TeamCustomerAnalyticsConfig",
"TeamDefaultEvaluationContext",
+ "TeamDataQualityConfig",
"TeamDataWarehouseConfig",
"TeamExperimentsConfig",
"TeamFeatureFlagsConfig",
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 06518f92b291..5a8e6dec6521 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -115,6 +115,9 @@ rules:
|DashboardWidget
|DataColorTheme
|DataModelingJob
+ |DataQualityCheck
+ |DataQualityCheckRun
+ |DataQualitySuiteRun
|Dataset
|DatasetItem
|DatasetItemVersion
@@ -464,6 +467,9 @@ rules:
|DashboardWidget
|DataColorTheme
|DataModelingJob
+ |DataQualityCheck
+ |DataQualityCheckRun
+ |DataQualitySuiteRun
|Dataset
|DatasetItem
|DatasetItemVersion
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 450e34846f9e..00bfc24669bd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2865,6 +2865,8 @@ importers:
specifier: 'catalog:'
+ products/data_quality: {}
+
products/data_tools: {}
products/data_warehouse:
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 799d19b8009b..fafd9ac01a48 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -101,6 +101,7 @@ ActivityScope = Literal[
"StreamlitApp",
"Metric",
"TableCertification",
+ "DataQualityCheck",
"Billing",
"Loop",
]
@@ -508,6 +509,16 @@ field_exclusions: dict[AuditableScope, list[str]] = {
"source_insight_query_hash",
"referenced_table_names",
],
+ "DataQualityCheck": [
+ # Written by the runner, not by a person editing the check.
+ "last_run_at",
+ "last_status",
+ "subject_name",
+ "subject_status",
+ # Subject FKs are immutable after create and not JSON-serializable for the change detail.
+ "saved_query",
+ "table",
+ ],
"Loop": [
# FK relations are not JSON-serializable for the change detail (same reason
# FeatureFlag/Subscription exclude theirs).
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index da21c637e2d9..3e6bc51e7e26 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -109,6 +109,7 @@ PRODUCTS_APPS = [
"products.approvals.backend.apps.ApprovalsConfig",
"products.pulse.backend.apps.PulseConfig",
"products.data_catalog.backend.apps.DataCatalogConfig",
+ "products.data_quality.backend.apps.DataQualityConfig",
]
INSTALLED_APPS = [
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index 10dd2e174d16..7339d9f65653 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -30,6 +30,7 @@ model_activity:products.business_knowledge.backend.signals.handle_knowledge_sour
model_activity:products.dashboards.backend.activity_logging.handle_dashboard_change
model_activity:products.dashboards.backend.activity_logging.handle_dashboard_widget_change
model_activity:products.data_catalog.backend.activity_logging.handle_metric_activity
+model_activity:products.data_quality.backend.activity_logging.handle_data_quality_check_activity
model_activity:products.data_tools.backend.activity_logging.handle_expression_activity
model_activity:products.experiments.backend.activity_logging.handle_experiment_change
model_activity:products.exports.backend.models.subscription.log_subscription_activity
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index 78d8a4c8ca3b..9d407dca899b 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -19,6 +19,8 @@ _LAZY = {
"update_node_type": "logic.saved_query_dag_sync",
"is_saved_query_on_v2_schedule": "logic.node_materialization",
"materialize_saved_query": "logic.node_materialization",
+ "get_saved_query_ids_for_nodes": "logic.saved_query_reads",
+ "get_saved_query_summary": "logic.saved_query_reads",
"saved_query_materialized_at": "logic.saved_query_freshness",
"start_node_materialization": "logic.node_materialization",
"apply_saved_query_frequency_anchor": "logic.schedule_reconcile",
diff --git a/products/data_modeling/backend/facade/contracts.py b/products/data_modeling/backend/facade/contracts.py
index 4240a11a10b8..c689229889aa 100644
--- a/products/data_modeling/backend/facade/contracts.py
+++ b/products/data_modeling/backend/facade/contracts.py
@@ -28,3 +28,18 @@ class DataModelingJob:
rows_expected: int | None
error: str | None
last_run_at: datetime
+
+
+@dataclass(frozen=True)
+class SavedQuerySummary:
+ """A saved query as other products need to see it: enough to name it and query it.
+
+ ``name`` is the HogQL identifier whether or not the view is materialized -- the physical backing
+ table is swapped in during resolution and is never the name a caller should query. That is also
+ why no materialization flag is exposed here: callers query the name either way.
+ """
+
+ id: str
+ team_id: int
+ name: str
+ last_run_at: datetime | None
diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.py
new file mode 100644
index 000000000000..f9082ff5b684
--- /dev/null
+++ b/products/data_modeling/backend/logic/saved_query_reads.py
@@ -0,0 +1,35 @@
+"""Contract-shaped reads of saved queries for consumers outside this product."""
+
+from collections.abc import Iterable
+from uuid import UUID
+
+from ..facade.contracts import SavedQuerySummary
+from ..models.datawarehouse_saved_query import DataWarehouseSavedQuery
+from ..models.node import Node
+
+
+def get_saved_query_summary(team_id: int, saved_query_id: UUID | str) -> SavedQuerySummary | None:
+ """The saved query only if it still resolves, else None.
+
+ Soft-deleted rows are excluded because ``soft_delete`` rewrites ``name`` to a tombstone -- a
+ caller holding a stored reference must not query that name.
+ """
+ saved_query = (
+ DataWarehouseSavedQuery.objects.filter(team_id=team_id, id=saved_query_id).exclude(deleted=True).first()
+ )
+ if saved_query is None:
+ return None
+ return SavedQuerySummary(
+ id=str(saved_query.id),
+ team_id=saved_query.team_id,
+ name=saved_query.name,
+ last_run_at=saved_query.last_run_at,
+ )
+
+
+def get_saved_query_ids_for_nodes(team_id: int, node_ids: Iterable[UUID | str]) -> list[str]:
+ """The saved queries behind these DAG nodes. Source-table nodes have none and are dropped."""
+ rows = Node.objects.filter(team_id=team_id, id__in=list(node_ids), saved_query__isnull=False).values_list(
+ "saved_query_id", flat=True
+ )
+ return [str(saved_query_id) for saved_query_id in rows]
diff --git a/products/data_quality/__init__.py b/products/data_quality/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/data_quality/backend/__init__.py b/products/data_quality/backend/__init__.py
new file mode 100644
index 000000000000..60413f1e0aad
--- /dev/null
+++ b/products/data_quality/backend/__init__.py
@@ -0,0 +1,2 @@
+# Package marker: without it this product's `tests` package resolves to a bare `tests`, which
+# collides with another product's when both suites run in one pytest invocation.
diff --git a/products/data_quality/backend/activity_logging.py b/products/data_quality/backend/activity_logging.py
new file mode 100644
index 000000000000..5081b7d52718
--- /dev/null
+++ b/products/data_quality/backend/activity_logging.py
@@ -0,0 +1,42 @@
+"""Activity-log receiver for data quality checks.
+
+``ModelActivityMixin`` emits ``model_activity_signal`` on every check save; this persists the audit
+trail (create, config change, soft delete). Registered from ``apps.ready()``.
+"""
+
+from typing import Any, Optional, cast
+
+from posthog.models import User
+from posthog.models.activity_logging.activity_log import AuditableScope, Detail, changes_between, log_activity
+from posthog.models.signals import model_activity_signal, mutable_receiver
+
+from .models import DataQualityCheck
+
+
+@mutable_receiver(model_activity_signal, sender=DataQualityCheck)
+def handle_data_quality_check_activity(
+ sender: type,
+ scope: str,
+ before_update: Optional[DataQualityCheck],
+ after_update: Optional[DataQualityCheck],
+ activity: str,
+ user: Optional[User],
+ was_impersonated: bool = False,
+ **kwargs: Any,
+) -> None:
+ instance = after_update or before_update
+ if instance is None:
+ return
+ log_activity(
+ organization_id=None,
+ team_id=instance.team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=str(instance.id),
+ scope=scope,
+ activity=activity,
+ detail=Detail(
+ name=str(instance),
+ changes=changes_between(cast(AuditableScope, scope), previous=before_update, current=after_update),
+ ),
+ )
diff --git a/products/data_quality/backend/admin.py b/products/data_quality/backend/admin.py
new file mode 100644
index 000000000000..c7fbc5585387
--- /dev/null
+++ b/products/data_quality/backend/admin.py
@@ -0,0 +1,21 @@
+from django.contrib import admin
+
+from products.data_quality.backend.facade.models import DataQualityCheck, DataQualitySuiteRun
+
+
[email protected](DataQualityCheck)
+class DataQualityCheckAdmin(admin.ModelAdmin):
+ list_display = ("id", "check_type", "subject_name", "column_name", "severity", "enabled", "last_status")
+ list_filter = ("check_type", "severity", "enabled", "subject_type", "subject_status")
+ search_fields = ("id", "name", "subject_name", "team__id")
+ raw_id_fields = ("team", "created_by", "owner", "saved_query", "table")
+ readonly_fields = ("id", "fingerprint", "created_at", "updated_at", "last_run_at", "last_status")
+
+
[email protected](DataQualitySuiteRun)
+class DataQualitySuiteRunAdmin(admin.ModelAdmin):
+ list_display = ("id", "trigger", "status", "checks_passed", "checks_failed", "checks_errored", "created_at")
+ list_filter = ("trigger", "status")
+ search_fields = ("id", "workflow_id", "team__id")
+ raw_id_fields = ("team", "created_by")
+ readonly_fields = ("id", "created_at", "updated_at", "started_at", "finished_at")
diff --git a/products/data_quality/backend/apps.py b/products/data_quality/backend/apps.py
new file mode 100644
index 000000000000..6de935e7719a
--- /dev/null
+++ b/products/data_quality/backend/apps.py
@@ -0,0 +1,12 @@
+"""Django app configuration for data_quality."""
+
+from django.apps import AppConfig
+
+
+class DataQualityConfig(AppConfig):
+ name = "products.data_quality.backend"
+ label = "data_quality"
+ verbose_name = "Data quality"
+
+ def ready(self) -> None:
+ from . import activity_logging # noqa: F401, PLC0415
diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.py
new file mode 100644
index 000000000000..0ea1ad957008
--- /dev/null
+++ b/products/data_quality/backend/facade/api.py
@@ -0,0 +1,32 @@
+"""
+Facade for data_quality.
+
+The only module this product's presentation layer (and external code) may import. It carries
+capability functions and frozen contracts, and nothing else: the check registry, the type specs and
+the AST-bearing ``CheckPlan`` stay inside ``logic``, since they are compiler internals rather than
+data. ORM model classes never cross here either -- ``facade/models.py`` is their one channel.
+"""
+
+from ..logic.compiler import compile_check, related_subject_ref
+from ..logic.contracts import CompiledCheck, SubjectRef
+from ..logic.errors import CheckConfigError, SubjectUnresolvableError
+from ..logic.registry import UnknownCheckTypeError, list_check_types
+from ..logic.serialization import compute_fingerprint, from_config_entry, to_config_entry
+from ..logic.subjects import resolve_subject
+from .contracts import CheckTypeInfo
+
+__all__ = [
+ "CheckConfigError",
+ "CheckTypeInfo",
+ "CompiledCheck",
+ "SubjectRef",
+ "SubjectUnresolvableError",
+ "UnknownCheckTypeError",
+ "compile_check",
+ "compute_fingerprint",
+ "from_config_entry",
+ "list_check_types",
+ "related_subject_ref",
+ "resolve_subject",
+ "to_config_entry",
+]
diff --git a/products/data_quality/backend/facade/contracts.py b/products/data_quality/backend/facade/contracts.py
new file mode 100644
index 000000000000..95ca332d433d
--- /dev/null
+++ b/products/data_quality/backend/facade/contracts.py
@@ -0,0 +1,22 @@
+"""
+Contract types for data_quality.
+
+Frozen, framework-free values other products need. No Django imports.
+"""
+
+from dataclasses import dataclass, field
+from typing import Any
+
+
+@dataclass(frozen=True)
+class CheckTypeInfo:
+ """One entry of the check-type catalog, so a caller can author config without guessing.
+
+ Carries what the registry knows about a type, flattened to plain values -- the spec object
+ itself stays internal, since it is a compiler, not data.
+ """
+
+ check_type: str
+ description: str
+ requires_column: bool
+ config_schema: dict[str, Any] = field(default_factory=dict)
diff --git a/products/data_quality/backend/facade/enums.py b/products/data_quality/backend/facade/enums.py
new file mode 100644
index 000000000000..e8d4228ad85e
--- /dev/null
+++ b/products/data_quality/backend/facade/enums.py
@@ -0,0 +1,101 @@
+"""
+Exported enums for data_quality.
+
+The pure, Django-free types other layers (presentation, information_schema loaders, MCP tooling)
+share. Internal-only constants stay in the implementation.
+"""
+
+from enum import StrEnum
+
+
+class CreatedSource(StrEnum):
+ """Who authored a check, for review context."""
+
+ USER = "user"
+ AI_GENERATED = "ai_generated"
+
+
+class CheckType(StrEnum):
+ """Assertion a data quality check makes about its subject.
+
+ Each value has a matching ``CheckTypeSpec`` in the check registry, which owns the config
+ schema and the HogQL compilation. Adding a type means adding a spec, not a migration.
+ """
+
+ NOT_NULL = "not_null"
+ UNIQUE = "unique"
+ ACCEPTED_VALUES = "accepted_values"
+ RELATIONSHIPS = "relationships"
+ ROW_COUNT = "row_count"
+ FRESHNESS = "freshness"
+ CUSTOM_SQL = "custom_sql"
+
+
+class CheckSeverity(StrEnum):
+ """How loudly a failing check speaks. Only ``error`` failures notify and mark a subject failing."""
+
+ ERROR = "error"
+ WARN = "warn"
+
+
+class CheckRunStatus(StrEnum):
+ """Outcome of one check execution.
+
+ ``failed`` means the assertion found failing rows; ``errored`` means the query could not be
+ compiled or executed, which is a different problem and never notifies as a data failure.
+ """
+
+ PASSED = "passed"
+ FAILED = "failed"
+ ERRORED = "errored"
+ SKIPPED = "skipped"
+
+
+class SuiteRunStatus(StrEnum):
+ """Lifecycle of a batch of check executions."""
+
+ RUNNING = "running"
+ COMPLETED = "completed"
+ FAILED = "failed"
+ EMPTY = "empty"
+
+
+class SuiteRunTrigger(StrEnum):
+ """What started a suite run.
+
+ Every automatic trigger is an event on the subject's own data -- a materialization or a source
+ sync completing. Checks have no independent schedule.
+ """
+
+ MANUAL = "manual"
+ MATERIALIZATION = "materialization"
+ SOURCE_SYNC = "source_sync"
+
+
+class SubjectType(StrEnum):
+ """Kind of catalog object a check targets.
+
+ On the check itself the subject is a foreign key (``saved_query`` for views, ``table`` for
+ warehouse tables); run history denormalizes it as loose ``(subject_type, subject_uuid, name)``
+ tuples so it outlives hard deletes.
+ """
+
+ TABLE = "table"
+ VIEW = "view"
+
+
+class SubjectStatus(StrEnum):
+ """Whether the subject a check points at still resolves."""
+
+ ACTIVE = "active"
+ ORPHANED = "orphaned"
+
+
+class SubjectHealth(StrEnum):
+ """Rollup of a subject's latest check results, shared by the REST endpoint and system table."""
+
+ HEALTHY = "healthy"
+ WARN = "warn"
+ FAILING = "failing"
+ ERRORING = "erroring"
+ UNKNOWN = "unknown"
diff --git a/products/data_quality/backend/facade/models.py b/products/data_quality/backend/facade/models.py
new file mode 100644
index 000000000000..c818f81852f1
--- /dev/null
+++ b/products/data_quality/backend/facade/models.py
@@ -0,0 +1,10 @@
+"""Model-class re-exports.
+
+The one place external code (information_schema loaders, admin, fixtures) and this product's own
+presentation layer are allowed to reach the ORM classes, keeping direct model imports off the
+isolation boundary.
+"""
+
+from ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun, TeamDataQualityConfig
+
+__all__ = ["DataQualityCheck", "DataQualityCheckRun", "DataQualitySuiteRun", "TeamDataQualityConfig"]
diff --git a/products/data_quality/backend/logic/__init__.py b/products/data_quality/backend/logic/__init__.py
new file mode 100644
index 000000000000..6f56615e38c4
--- /dev/null
+++ b/products/data_quality/backend/logic/__init__.py
@@ -0,0 +1,5 @@
+"""Data quality checks: registry, compiler, subject resolution, canonical serialization.
+
+Import the specific module you need. The registry is the extension point -- a new check type is a
+new ``CheckTypeSpec``, never a schema migration.
+"""
diff --git a/products/data_quality/backend/logic/compiler.py b/products/data_quality/backend/logic/compiler.py
new file mode 100644
index 000000000000..06e9c5bc37cd
--- /dev/null
+++ b/products/data_quality/backend/logic/compiler.py
@@ -0,0 +1,70 @@
+"""Turn a check definition into one count-only aggregate HogQL query.
+
+Every check compiles to ``SELECT <aggregates> FROM (<failing rows>)``. Rows never leave
+ClickHouse: the outer query only ever projects counts and numeric aggregates, which is what makes
+it safe to store the result in the main Postgres.
+
+``WarehouseColumnStatistics`` could short-circuit some of these (null counts, distinct counts) but
+only for synced source tables at sync time, which is a second, subtly different set of semantics.
+Left as a future fast-path rather than a silent inconsistency.
+"""
+
+from typing import Any
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.printer import print_prepared_ast
+
+from .contracts import CheckPlan, CompiledCheck, Evaluation, SubjectRef
+from .errors import SubjectUnresolvableError
+from .registry import get_spec
+
+FAILURE_COUNT_ALIAS = "failure_count"
+OBSERVED_VALUE_ALIAS = "observed_value"
+
+
+def compile_check(
+ *,
+ check_type: str,
+ subject: SubjectRef,
+ column_name: str,
+ config: dict[str, Any],
+ related_subject: SubjectRef | None = None,
+) -> CompiledCheck:
+ if not subject.exists:
+ raise SubjectUnresolvableError(f"The {subject.subject_type} {subject.subject_uuid} no longer resolves.")
+
+ spec = get_spec(check_type)
+ plan = spec.build(subject, column_name, spec.validate(config, column_name), related_subject)
+ query = _aggregate(plan)
+ return CompiledCheck(
+ query=query,
+ printed_query=_print(query),
+ printed_failing_rows_query=_print(plan.diagnostic_rows or plan.failing_rows),
+ evaluation=plan.evaluation,
+ )
+
+
+def _print(query: "ast.SelectQuery | ast.SelectSetQuery") -> str:
+ # limit_top_select=False: the aggregate is a single row anyway, and the failing-rows form is
+ # stored for a human to re-run, so a synthetic LIMIT would misrepresent what the check examined.
+ return print_prepared_ast(
+ query,
+ context=HogQLContext(enable_select_queries=True, limit_top_select=False),
+ dialect="hogql",
+ )
+
+
+def related_subject_ref(check_type: str, config: dict[str, Any]) -> tuple[str, str] | None:
+ """The second subject this check needs resolved before it can compile, if any."""
+ spec = get_spec(check_type)
+ return spec.related_subject_ref(spec.parse_config(config))
+
+
+def _aggregate(plan: CheckPlan) -> ast.SelectQuery:
+ count_all = ast.Call(name="count", args=[])
+ selects: list[ast.Expr] = []
+ if plan.evaluation is Evaluation.ZERO_ROWS_PASS:
+ selects.append(ast.Alias(alias=FAILURE_COUNT_ALIAS, expr=plan.failed_count_expr or count_all))
+ selects.append(ast.Alias(alias=OBSERVED_VALUE_ALIAS, expr=plan.observed_value_expr or count_all))
+ return ast.SelectQuery(select=selects, select_from=ast.JoinExpr(table=plan.failing_rows))
diff --git a/products/data_quality/backend/logic/contracts.py b/products/data_quality/backend/logic/contracts.py
new file mode 100644
index 000000000000..86b5006ac2b8
--- /dev/null
+++ b/products/data_quality/backend/logic/contracts.py
@@ -0,0 +1,68 @@
+"""Shapes passed between the subject resolver, the check registry, and the compiler."""
+
+from dataclasses import dataclass
+from enum import StrEnum
+from typing import TYPE_CHECKING
+
+from ..facade.enums import SubjectType
+
+if TYPE_CHECKING:
+ from posthog.hogql import ast
+
+
+class Evaluation(StrEnum):
+ """How the runner turns a compiled query's result row into a status."""
+
+ ZERO_ROWS_PASS = "zero_rows_pass"
+ BOUNDS = "bounds"
+
+
+@dataclass(frozen=True)
+class SubjectRef:
+ """A resolved check subject.
+
+ ``queryable_name`` is what the compiler puts in the FROM clause; it can differ from the stored
+ ``subject_name`` after a rename, which is why the runner writes it back to the check row.
+ """
+
+ subject_type: SubjectType
+ subject_uuid: str
+ name: str
+ queryable_name: str
+ exists: bool
+
+
+@dataclass(frozen=True)
+class CheckPlan:
+ """What a check type contributes to the compiled query.
+
+ ``failing_rows`` selects the rows that violate the assertion; the compiler aggregates over it so
+ nothing but counts ever leaves ClickHouse. A type whose headline number is not a row count
+ (freshness) overrides ``failed_count_expr`` and ``observed_value_expr``.
+
+ ``diagnostic_rows`` is the form a human re-runs. It exists because the two jobs pull apart:
+ counting is cheapest over a constant projection, while investigating needs the offending values.
+ A type whose failing rows already show something useful leaves it unset.
+ """
+
+ failing_rows: "ast.SelectQuery | ast.SelectSetQuery"
+ diagnostic_rows: "ast.SelectQuery | ast.SelectSetQuery | None" = None
+ failed_count_expr: "ast.Expr | None" = None
+ observed_value_expr: "ast.Expr | None" = None
+ evaluation: Evaluation = Evaluation.ZERO_ROWS_PASS
+
+
+@dataclass(frozen=True)
+class CompiledCheck:
+ """A check ready to execute.
+
+ Two printed forms, because they answer different questions. ``printed_query`` is the aggregate
+ that actually runs. ``printed_failing_rows_query`` is the inner query on its own, which is what
+ someone investigating a failure needs: since failing rows are never stored, re-running this is
+ the only way to see them.
+ """
+
+ query: "ast.SelectQuery"
+ printed_query: str
+ printed_failing_rows_query: str
+ evaluation: Evaluation
diff --git a/products/data_quality/backend/logic/errors.py b/products/data_quality/backend/logic/errors.py
new file mode 100644
index 000000000000..0f86133e7a90
--- /dev/null
+++ b/products/data_quality/backend/logic/errors.py
@@ -0,0 +1,13 @@
+"""Errors raised while validating or compiling a check.
+
+Plain exceptions, not DRF ``APIException``s: these are raised from Temporal activities as well as
+from serializers, and the presentation layer is responsible for mapping them to a status code.
+"""
+
+
+class CheckConfigError(ValueError):
+ """The check's config, column, or custom query is unusable for its type."""
+
+
+class SubjectUnresolvableError(ValueError):
+ """The subject a check targets no longer resolves in its owning product."""
diff --git a/products/data_quality/backend/logic/registry.py b/products/data_quality/backend/logic/registry.py
new file mode 100644
index 000000000000..47b4227f7fdf
--- /dev/null
+++ b/products/data_quality/backend/logic/registry.py
@@ -0,0 +1,53 @@
+"""Registry of the available check types.
+
+The spec contract itself lives in ``spec.py``; this is only the lookup table, so adding a type is
+one import and one entry.
+"""
+
+from ..facade.contracts import CheckTypeInfo
+from ..facade.enums import CheckType
+from .spec import CheckTypeSpec
+from .types import accepted_values, custom_sql, freshness, not_null, relationships, row_count, unique
+
+_SPECS: dict[CheckType, CheckTypeSpec] = {
+ spec.type_name: spec
+ for spec in (
+ not_null.SPEC,
+ unique.SPEC,
+ accepted_values.SPEC,
+ relationships.SPEC,
+ row_count.SPEC,
+ freshness.SPEC,
+ custom_sql.SPEC,
+ )
+}
+
+
+def get_spec(check_type: str) -> CheckTypeSpec:
+ try:
+ return _SPECS[CheckType(check_type)]
+ except (KeyError, ValueError):
+ raise UnknownCheckTypeError(check_type)
+
+
+def all_specs() -> list[CheckTypeSpec]:
+ return [_SPECS[check_type] for check_type in CheckType]
+
+
+def list_check_types() -> list[CheckTypeInfo]:
+ """The catalog, as plain values. What callers outside the compiler get instead of the specs."""
+ return [
+ CheckTypeInfo(
+ check_type=spec.type_name.value,
+ description=spec.description,
+ requires_column=spec.requires_column,
+ config_schema=spec.json_schema,
+ )
+ for spec in all_specs()
+ ]
+
+
+class UnknownCheckTypeError(ValueError):
+ def __init__(self, check_type: str) -> None:
+ supported = ", ".join(t.value for t in CheckType)
+ super().__init__(f"Unknown check type '{check_type}'. Supported types: {supported}.")
diff --git a/products/data_quality/backend/logic/serialization.py b/products/data_quality/backend/logic/serialization.py
new file mode 100644
index 000000000000..954f54625e2e
--- /dev/null
+++ b/products/data_quality/backend/logic/serialization.py
@@ -0,0 +1,77 @@
+"""Canonical form of a check definition, and the fingerprint derived from it.
+
+No Django imports. This is the module a future git-sync would call to project checks into config
+files and read them back: the DB stays the source of truth, files are a projection, and
+``CheckConfigEntry`` is the shape that round-trips between them without a migration.
+
+The fingerprint is the identity agents author against -- re-creating a semantically identical check
+upserts instead of duplicating -- so it must depend only on what the check *asserts*, never on
+presentation (name, description, tags, owner). ``subject_uuid`` here is the id of whichever subject
+FK the check carries (saved query or table); the file format keeps the loose pair so it stays
+portable.
+"""
+
+import json
+import hashlib
+from typing import Any
+from uuid import UUID
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from ..facade.enums import CheckSeverity, CheckType, SubjectType
+
+
+class CheckConfigEntry(BaseModel):
+ """A check as a config file would hold it.
+
+ Extras are ignored rather than rejected so this can be built straight from a full check row,
+ which carries ids and timestamps a file never would.
+ """
+
+ model_config = ConfigDict(extra="ignore")
+
+ name: str = ""
+ description: str = ""
+ subject_type: SubjectType
+ subject_uuid: UUID
+ column_name: str = ""
+ check_type: CheckType
+ config: dict[str, Any] = Field(default_factory=dict)
+ severity: CheckSeverity = CheckSeverity.ERROR
+ enabled: bool = True
+ tags: list[str] = Field(default_factory=list)
+
+
+def to_config_entry(check: dict[str, Any]) -> dict[str, Any]:
+ """Project a check into its portable config-file representation."""
+ return CheckConfigEntry.model_validate(check).model_dump(mode="json")
+
+
+def from_config_entry(entry: dict[str, Any]) -> dict[str, Any]:
+ """Read a config-file entry back into check fields, filling defaults for anything omitted."""
+ return CheckConfigEntry.model_validate(entry).model_dump()
+
+
+def compute_fingerprint(
+ *,
+ subject_type: str,
+ subject_uuid: str,
+ check_type: str,
+ column_name: str,
+ config: dict[str, Any],
+) -> str:
+ """Hash what the check asserts.
+
+ ``config`` must already be normalized: pass ``spec.validate(...).model_dump(mode="json")``, not
+ raw request data. Normalizing through the type's model first means two configs differing only in
+ representation (``1`` vs ``1.0``, key order, a stringified number) land on the same fingerprint
+ and upsert, instead of quietly creating a near-duplicate check.
+ """
+ payload = {
+ "subject_type": str(subject_type),
+ "subject_uuid": str(subject_uuid),
+ "check_type": str(check_type),
+ "column_name": column_name,
+ "config": config,
+ }
+ return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
diff --git a/products/data_quality/backend/logic/spec.py b/products/data_quality/backend/logic/spec.py
new file mode 100644
index 000000000000..ac4a29cec6d3
--- /dev/null
+++ b/products/data_quality/backend/logic/spec.py
@@ -0,0 +1,83 @@
+"""The check-type extension point.
+
+A check type is a ``CheckTypeSpec``: a Pydantic config model plus a compiler. Everything else is
+derived. The JSON schema the API and MCP tools publish comes from ``model_json_schema()``, and
+validation is ``model_validate``, so the config shape is declared once as typed fields instead of
+being hand-written twice (as a schema and as a validator) and drifting.
+
+Adding anomaly detection or unit tests later means adding a spec, not migrating the schema.
+"""
+
+from abc import ABC, abstractmethod
+from typing import Any, ClassVar
+
+from pydantic import BaseModel, ConfigDict, ValidationError
+
+from ..facade.enums import CheckType
+from .contracts import CheckPlan, SubjectRef
+from .errors import CheckConfigError
+
+
+class CheckConfig(BaseModel):
+ """Base for every check type's config. Unknown keys are a mistake worth reporting, not ignoring."""
+
+ model_config = ConfigDict(extra="forbid")
+
+
+class NoConfig(CheckConfig):
+ """For types whose column is the whole configuration."""
+
+
+class CheckTypeSpec(ABC):
+ """What every check type must provide.
+
+ An ABC rather than a Protocol so a spec that forgets a field or gets a signature wrong fails at
+ import, not on the first agent that tries to use it.
+ """
+
+ type_name: ClassVar[CheckType]
+ config_model: ClassVar[type[CheckConfig]]
+ requires_column: ClassVar[bool]
+ description: ClassVar[str]
+
+ @property
+ def json_schema(self) -> dict[str, Any]:
+ """Published by the check_types endpoint and the MCP tool docs. Generated, never written."""
+ return self.config_model.model_json_schema()
+
+ def parse_config(self, config: dict[str, Any]) -> CheckConfig:
+ """Validate raw config into this type's model, or raise ``CheckConfigError``.
+
+ Config only. The column is a separate axis, so callers that just need to read the config
+ (resolving a related subject, say) do not have to supply one.
+ """
+ try:
+ return self.config_model.model_validate(config or {})
+ except ValidationError as err:
+ raise CheckConfigError(f"Invalid config for a {self.type_name} check: {_first_problem(err)}")
+
+ def validate(self, config: dict[str, Any], column_name: str) -> CheckConfig:
+ """Everything a check needs to be compilable: a usable config and, where required, a column."""
+ if self.requires_column and not column_name:
+ raise CheckConfigError(f"A {self.type_name} check needs a column_name.")
+ return self.parse_config(config)
+
+ def related_subject_ref(self, config: CheckConfig) -> tuple[str, str] | None:
+ """The second subject this check needs resolved before it can compile, if any."""
+ return None
+
+ @abstractmethod
+ def build(
+ self,
+ subject: SubjectRef,
+ column_name: str,
+ config: CheckConfig,
+ related: SubjectRef | None = None,
+ ) -> CheckPlan:
+ """Select the rows that violate the assertion. The compiler aggregates over them."""
+
+
+def _first_problem(err: ValidationError) -> str:
+ problem = err.errors()[0]
+ location = ".".join(str(part) for part in problem["loc"]) or "config"
+ return f"{location}: {problem['msg']}"
diff --git a/products/data_quality/backend/logic/subjects.py b/products/data_quality/backend/logic/subjects.py
new file mode 100644
index 000000000000..195a7674fc33
--- /dev/null
+++ b/products/data_quality/backend/logic/subjects.py
@@ -0,0 +1,59 @@
+"""Resolve a check's subject id to something queryable.
+
+The check row carries the subject as a foreign key (``saved_query`` or ``table``); resolution still
+goes through the owning product's facade rather than traversing the FK, so model instances never
+cross the product boundary. A subject that no longer resolves marks the check orphaned, and the
+denormalized name is refreshed on every run so renames self-heal.
+"""
+
+from uuid import UUID
+
+from products.data_modeling.backend.facade import api as data_modeling_facade
+from products.warehouse_sources.backend.facade import api as warehouse_facade
+
+from ..facade.enums import SubjectType
+from .contracts import SubjectRef
+
+
+def resolve_subject(team_id: int, subject_type: str, subject_uuid: str | UUID) -> SubjectRef:
+ """Look the subject up in its owning product. Never raises for a missing subject."""
+ kind = SubjectType(subject_type)
+ if kind is SubjectType.TABLE:
+ return _resolve_table(team_id, subject_uuid)
+ return _resolve_view(team_id, subject_uuid)
+
+
+def _resolve_table(team_id: int, subject_uuid: str | UUID) -> SubjectRef:
+ table = warehouse_facade.get_queryable_table(UUID(str(subject_uuid)), team_id)
+ if table is None:
+ return _missing(SubjectType.TABLE, subject_uuid)
+ return SubjectRef(
+ subject_type=SubjectType.TABLE,
+ subject_uuid=str(subject_uuid),
+ name=table.name,
+ queryable_name=table.name,
+ exists=True,
+ )
+
+
+def _resolve_view(team_id: int, subject_uuid: str | UUID) -> SubjectRef:
+ saved_query = data_modeling_facade.get_saved_query_summary(team_id, subject_uuid)
+ if saved_query is None:
+ return _missing(SubjectType.VIEW, subject_uuid)
+ return SubjectRef(
+ subject_type=SubjectType.VIEW,
+ subject_uuid=str(subject_uuid),
+ name=saved_query.name,
+ queryable_name=saved_query.name,
+ exists=True,
+ )
+
+
+def _missing(kind: SubjectType, subject_uuid: str | UUID) -> SubjectRef:
+ return SubjectRef(
+ subject_type=kind,
+ subject_uuid=str(subject_uuid),
+ name="",
+ queryable_name="",
+ exists=False,
+ )
diff --git a/products/data_quality/backend/logic/types/__init__.py b/products/data_quality/backend/logic/types/__init__.py
new file mode 100644
index 000000000000..e157fdb4dbd0
--- /dev/null
+++ b/products/data_quality/backend/logic/types/__init__.py
@@ -0,0 +1 @@
+"""One module per check type. Each exports a ``SPEC`` that the registry collects."""
diff --git a/products/data_quality/backend/logic/types/accepted_values.py b/products/data_quality/backend/logic/types/accepted_values.py
new file mode 100644
index 000000000000..94e9f4c56e70
--- /dev/null
+++ b/products/data_quality/backend/logic/types/accepted_values.py
@@ -0,0 +1,56 @@
+import json
+
+from pydantic import Field, field_validator
+
+from posthog.hogql import ast
+
+from ...facade.enums import CheckType
+from ..contracts import CheckPlan, SubjectRef
+from ..spec import CheckConfig, CheckTypeSpec
+from .common import column, diagnostic_of, one, subject_source
+
+
+class AcceptedValuesConfig(CheckConfig):
+ values: list[str | float | bool] = Field(
+ min_length=1, description="The complete set of values the column is allowed to take."
+ )
+
+ @field_validator("values")
+ @classmethod
+ def _canonical_set(cls, values: list[str | float | bool]) -> list[str | float | bool]:
+ # values is semantically a set: dedupe and order deterministically (by JSON representation,
+ # which totally orders across the mixed value types) so two configs differing only in
+ # ordering or repetition normalize identically and upsert instead of creating a twin.
+ by_repr = {json.dumps(value, sort_keys=True): value for value in values}
+ return [by_repr[key] for key in sorted(by_repr)]
+
+
+class AcceptedValuesSpec(CheckTypeSpec):
+ type_name = CheckType.ACCEPTED_VALUES
+ config_model = AcceptedValuesConfig
+ requires_column = True
+ description = "Fails on rows whose column value is outside the allowed set. Nulls are ignored."
+
+ def build(
+ self, subject: SubjectRef, column_name: str, config: CheckConfig, related: SubjectRef | None = None
+ ) -> CheckPlan:
+ assert isinstance(config, AcceptedValuesConfig)
+ value = column(column_name)
+ failing_rows = ast.SelectQuery(
+ select=[one()],
+ select_from=subject_source(subject),
+ where=ast.And(
+ exprs=[
+ ast.Call(name="isNotNull", args=[value]),
+ ast.CompareOperation(
+ left=value,
+ op=ast.CompareOperationOp.NotIn,
+ right=ast.Constant(value=list(config.values)),
+ ),
+ ]
+ ),
+ )
+ return CheckPlan(failing_rows=failing_rows, diagnostic_rows=diagnostic_of(failing_rows))
+
+
+SPEC = AcceptedValuesSpec()
diff --git a/products/data_quality/backend/logic/types/common.py b/products/data_quality/backend/logic/types/common.py
new file mode 100644
index 000000000000..ea98dc24ccfe
--- /dev/null
+++ b/products/data_quality/backend/logic/types/common.py
@@ -0,0 +1,33 @@
+"""Shared building blocks for check-type specs.
+
+Every identifier reaching a query goes through a HogQL AST node, never string interpolation, so
+the printer's backtick escaping is the only thing standing between a hostile column name and the
+generated SQL.
+"""
+
+from posthog.hogql import ast
+
+from ..contracts import SubjectRef
+
+
+def subject_source(subject: SubjectRef) -> ast.JoinExpr:
+ return ast.JoinExpr(table=ast.Field(chain=list(subject.queryable_name.split("."))))
+
+
+def column(column_name: str) -> ast.Field:
+ return ast.Field(chain=list(column_name.split(".")))
+
+
+def one() -> ast.Constant:
+ """Placeholder projection for subqueries whose rows matter but whose values do not."""
+ return ast.Constant(value=1)
+
+
+def star() -> ast.Field:
+ """Projection for the diagnostic form, where the offending row is the whole point."""
+ return ast.Field(chain=["*"])
+
+
+def diagnostic_of(failing_rows: ast.SelectQuery) -> ast.SelectQuery:
+ """The same rows the check counts, projected so a human can see what broke."""
+ return ast.SelectQuery(select=[star()], select_from=failing_rows.select_from, where=failing_rows.where)
diff --git a/products/data_quality/backend/logic/types/custom_sql.py b/products/data_quality/backend/logic/types/custom_sql.py
new file mode 100644
index 000000000000..f1102bf1cb91
--- /dev/null
+++ b/products/data_quality/backend/logic/types/custom_sql.py
@@ -0,0 +1,69 @@
+from pydantic import Field, field_validator
+
+from posthog.hogql import ast
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.parser import parse_select
+from posthog.hogql.placeholders import find_placeholders
+
+from ...facade.enums import CheckType
+from ..contracts import CheckPlan, SubjectRef
+from ..errors import CheckConfigError
+from ..spec import CheckConfig, CheckTypeSpec
+
+
+def parse_failing_rows_query(query: str) -> ast.SelectQuery | ast.SelectSetQuery:
+ """Parse user HogQL into the SELECT whose rows are the failures.
+
+ A UNION of selects is as good as one: the compiler aggregates over whatever this returns, so the
+ failure set can be assembled from several branches.
+ """
+ try:
+ parsed = parse_select(query.rstrip(";").strip())
+ except ExposedHogQLError as err:
+ raise CheckConfigError(f"Could not parse the custom query: {err}")
+ except Exception:
+ raise CheckConfigError("Could not parse the custom query.")
+
+ found = find_placeholders(parsed)
+ if found.has_filters or found.placeholder_fields or found.placeholder_expressions:
+ raise CheckConfigError("A custom_sql check cannot use {placeholders} -- nothing supplies them.")
+ return parsed
+
+
+class CustomSqlConfig(CheckConfig):
+ query: str = Field(
+ min_length=1,
+ description="HogQL SELECT returning one row per failure. Passing means it returns nothing.",
+ )
+
+ @field_validator("query")
+ @classmethod
+ def _is_a_select(cls, value: str) -> str:
+ parse_failing_rows_query(value)
+ return value
+
+
+class CustomSqlSpec(CheckTypeSpec):
+ """A user-written HogQL SELECT whose returned rows are the failures.
+
+ No extra sandboxing: HogQL is already team-scoped and read-only, and the query is wrapped in a
+ count so rows never leave ClickHouse. Placeholders are rejected because nothing supplies them.
+
+ Nothing forces the query to read the check's own subject -- the subject decides when the check
+ runs and where its result is reported, not what the SQL may touch. A check whose query reads
+ elsewhere is therefore possible, and reports against the wrong table.
+ """
+
+ type_name = CheckType.CUSTOM_SQL
+ config_model = CustomSqlConfig
+ requires_column = False
+ description = "Fails on every row the custom HogQL SELECT returns."
+
+ def build(
+ self, subject: SubjectRef, column_name: str, config: CheckConfig, related: SubjectRef | None = None
+ ) -> CheckPlan:
+ assert isinstance(config, CustomSqlConfig)
+ return CheckPlan(failing_rows=parse_failing_rows_query(config.query))
+
+
+SPEC = CustomSqlSpec()
diff --git a/products/data_quality/backend/logic/types/freshness.py b/products/data_quality/backend/logic/types/freshness.py
new file mode 100644
index 000000000000..82e4ee186009
--- /dev/null
+++ b/products/data_quality/backend/logic/types/freshness.py
@@ -0,0 +1,73 @@
+from pydantic import Field
+
+from posthog.hogql import ast
+
+from ...facade.enums import CheckType
+from ..contracts import CheckPlan, SubjectRef
+from ..spec import CheckConfig, CheckTypeSpec
+from .common import column, subject_source
+
+STALENESS_ALIAS = "staleness_seconds"
+SECONDS_PER_MINUTE = 60
+
+
+class FreshnessConfig(CheckConfig):
+ max_age_minutes: int = Field(
+ ge=1, description="Fail when the newest value in the column is older than this many minutes."
+ )
+
+
+class FreshnessSpec(CheckTypeSpec):
+ """How long ago the newest row landed.
+
+ The inner query always returns exactly one row, so staleness is recorded as a time series even
+ on a pass -- that series is what anomaly-detection check types will train on.
+ """
+
+ type_name = CheckType.FRESHNESS
+ config_model = FreshnessConfig
+ requires_column = True
+ description = "Fails when the newest timestamp in the column is older than max_age_minutes."
+
+ def build(
+ self, subject: SubjectRef, column_name: str, config: CheckConfig, related: SubjectRef | None = None
+ ) -> CheckPlan:
+ assert isinstance(config, FreshnessConfig)
+ staleness = ast.Field(chain=[STALENESS_ALIAS])
+ threshold = ast.Constant(value=config.max_age_minutes * SECONDS_PER_MINUTE)
+ return CheckPlan(
+ failing_rows=ast.SelectQuery(
+ select=[
+ ast.Alias(
+ alias=STALENESS_ALIAS,
+ expr=ast.Call(
+ name="dateDiff",
+ args=[
+ ast.Constant(value="second"),
+ ast.Call(name="max", args=[column(column_name)]),
+ ast.Call(name="now", args=[]),
+ ],
+ ),
+ )
+ ],
+ select_from=subject_source(subject),
+ ),
+ # A null staleness means the column has no non-null value at all: an empty table, or a
+ # pipeline that never wrote. That is exactly what freshness exists to catch, so it has to
+ # count as a failure -- a bare `staleness > threshold` against null yields 0 and passes.
+ failed_count_expr=ast.Call(
+ name="countIf",
+ args=[
+ ast.Or(
+ exprs=[
+ ast.Call(name="isNull", args=[staleness]),
+ ast.CompareOperation(left=staleness, op=ast.CompareOperationOp.Gt, right=threshold),
+ ]
+ )
+ ],
+ ),
+ observed_value_expr=ast.Call(name="max", args=[staleness]),
+ )
+
+
+SPEC = FreshnessSpec()
diff --git a/products/data_quality/backend/logic/types/not_null.py b/products/data_quality/backend/logic/types/not_null.py
new file mode 100644
index 000000000000..715432b758d9
--- /dev/null
+++ b/products/data_quality/backend/logic/types/not_null.py
@@ -0,0 +1,26 @@
+from posthog.hogql import ast
+
+from ...facade.enums import CheckType
+from ..contracts import CheckPlan, SubjectRef
+from ..spec import CheckConfig, CheckTypeSpec, NoConfig
+from .common import column, diagnostic_of, one, subject_source
+
+
+class NotNullSpec(CheckTypeSpec):
+ type_name = CheckType.NOT_NULL
+ config_model = NoConfig
+ requires_column = True
+ description = "Fails on rows where the column is null."
+
+ def build(
+ self, subject: SubjectRef, column_name: str, config: CheckConfig, related: SubjectRef | None = None
+ ) -> CheckPlan:
+ failing_rows = ast.SelectQuery(
+ select=[one()],
+ select_from=subject_source(subject),
+ where=ast.Call(name="isNull", args=[column(column_name)]),
+ )
+ return CheckPlan(failing_rows=failing_rows, diagnostic_rows=diagnostic_of(failing_rows))
+
+
+SPEC = NotNullSpec()
diff --git a/products/data_quality/backend/logic/types/relationships.py b/products/data_quality/backend/logic/types/relationships.py
new file mode 100644
index 000000000000..13db238272f6
--- /dev/null
+++ b/products/data_quality/backend/logic/types/relationships.py
@@ -0,0 +1,58 @@
+from uuid import UUID
+
+from pydantic import Field
+
+from posthog.hogql import ast
+
+from ...facade.enums import CheckType, SubjectType
+from ..contracts import CheckPlan, SubjectRef
+from ..errors import SubjectUnresolvableError
+from ..spec import CheckConfig, CheckTypeSpec
+from .common import column, diagnostic_of, one, subject_source
+
+
+class RelationshipsConfig(CheckConfig):
+ to_subject_type: SubjectType = Field(description="Kind of catalog object holding the referenced values.")
+ to_subject_uuid: UUID = Field(description="Id of the table or view holding the referenced values.")
+ to_column: str = Field(min_length=1, description="Column holding the referenced values.")
+
+
+class RelationshipsSpec(CheckTypeSpec):
+ """Referential integrity: every non-null value must exist in another subject's column."""
+
+ type_name = CheckType.RELATIONSHIPS
+ config_model = RelationshipsConfig
+ requires_column = True
+ description = "Fails on rows whose column value has no match in the referenced subject's column."
+
+ def related_subject_ref(self, config: CheckConfig) -> tuple[str, str] | None:
+ assert isinstance(config, RelationshipsConfig)
+ return str(config.to_subject_type), str(config.to_subject_uuid)
+
+ def build(
+ self, subject: SubjectRef, column_name: str, config: CheckConfig, related: SubjectRef | None = None
+ ) -> CheckPlan:
+ assert isinstance(config, RelationshipsConfig)
+ if related is None or not related.exists:
+ raise SubjectUnresolvableError(
+ f"The referenced {config.to_subject_type} {config.to_subject_uuid} no longer resolves."
+ )
+ value = column(column_name)
+ referenced = ast.SelectQuery(
+ select=[column(config.to_column)],
+ select_from=subject_source(related),
+ )
+ failing_rows = ast.SelectQuery(
+ select=[one()],
+ select_from=subject_source(subject),
+ where=ast.And(
+ exprs=[
+ ast.Call(name="isNotNull", args=[value]),
+ ast.CompareOperation(left=value, op=ast.CompareOperationOp.NotIn, right=referenced),
+ ]
+ ),
+ )
+ return CheckPlan(failing_rows=failing_rows, diagnostic_rows=diagnostic_of(failing_rows))
+
+
+SPEC = RelationshipsSpec()
diff --git a/products/data_quality/backend/logic/types/row_count.py b/products/data_quality/backend/logic/types/row_count.py
new file mode 100644
index 000000000000..572492c5be12
--- /dev/null
+++ b/products/data_quality/backend/logic/types/row_count.py
@@ -0,0 +1,53 @@
+from typing import Self
+
+from pydantic import Field, model_validator
+
+from posthog.hogql import ast
+
+from ...facade.enums import CheckType
+from ..contracts import CheckPlan, Evaluation, SubjectRef
+from ..spec import CheckConfig, CheckTypeSpec
+from .common import one, subject_source
+
+ROW_COUNT_ALIAS = "row_count"
+
+
+class RowCountConfig(CheckConfig):
+ min: int | None = Field(default=None, ge=0, description="Fail if the table has fewer rows than this.")
+ max: int | None = Field(default=None, ge=0, description="Fail if the table has more rows than this.")
+
+ @model_validator(mode="after")
+ def _bounds_are_usable(self) -> Self:
+ if self.min is None and self.max is None:
+ raise ValueError("needs at least one of min or max")
+ if self.min is not None and self.max is not None and self.min > self.max:
+ raise ValueError(f"needs min <= max, got min={self.min} and max={self.max}")
+ return self
+
+
+class RowCountSpec(CheckTypeSpec):
+ """The one type that does not use zero-failing-rows semantics: it compares a count to bounds."""
+
+ type_name = CheckType.ROW_COUNT
+ config_model = RowCountConfig
+ requires_column = False
+ description = "Fails when the table's row count falls outside min/max. At least one bound is required."
+
+ def build(
+ self, subject: SubjectRef, column_name: str, config: CheckConfig, related: SubjectRef | None = None
+ ) -> CheckPlan:
+ return CheckPlan(
+ failing_rows=ast.SelectQuery(select=[one()], select_from=subject_source(subject)),
+ # No row is individually at fault here, so the diagnostic is the number the bounds were
+ # compared against rather than a projection of every row in the table.
+ diagnostic_rows=ast.SelectQuery(
+ select=[ast.Alias(alias=ROW_COUNT_ALIAS, expr=ast.Call(name="count", args=[]))],
+ select_from=subject_source(subject),
+ ),
+ failed_count_expr=None,
+ observed_value_expr=ast.Call(name="count", args=[]),
+ evaluation=Evaluation.BOUNDS,
+ )
+
+
+SPEC = RowCountSpec()
diff --git a/products/data_quality/backend/logic/types/unique.py b/products/data_quality/backend/logic/types/unique.py
new file mode 100644
index 000000000000..a022f2136a2a
--- /dev/null
+++ b/products/data_quality/backend/logic/types/unique.py
@@ -0,0 +1,34 @@
+from posthog.hogql import ast
+
+from ...facade.enums import CheckType
+from ..contracts import CheckPlan, SubjectRef
+from ..spec import CheckConfig, CheckTypeSpec, NoConfig
+from .common import column, subject_source
+
+
+class UniqueSpec(CheckTypeSpec):
+ type_name = CheckType.UNIQUE
+ config_model = NoConfig
+ requires_column = True
+ description = "Fails once per column value that appears more than once. Nulls are ignored."
+
+ def build(
+ self, subject: SubjectRef, column_name: str, config: CheckConfig, related: SubjectRef | None = None
+ ) -> CheckPlan:
+ value = column(column_name)
+ return CheckPlan(
+ failing_rows=ast.SelectQuery(
+ select=[value],
+ select_from=subject_source(subject),
+ where=ast.Call(name="isNotNull", args=[value]),
+ group_by=[value],
+ having=ast.CompareOperation(
+ left=ast.Call(name="count", args=[]),
+ op=ast.CompareOperationOp.Gt,
+ right=ast.Constant(value=1),
+ ),
+ )
+ )
+
+
+SPEC = UniqueSpec()
diff --git a/products/data_quality/backend/migrations/0001_initial.py b/products/data_quality/backend/migrations/0001_initial.py
new file mode 100644
index 000000000000..19fc09c00855
--- /dev/null
+++ b/products/data_quality/backend/migrations/0001_initial.py
@@ -0,0 +1,569 @@
+# Generated by Django 5.2.14 on 2026-08-06 20:40
+
+import django.core.validators
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+import products.data_quality.backend.facade.enums
+import products.data_quality.backend.models.check
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = [
+ ("data_modeling", "0028_alter_datawarehousemanagedviewset_kind"),
+ ("posthog", "1290_backfill_identity_provider_config_identifiers"),
+ ("warehouse_sources", "0118_scaffold_sevalla_source"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="TeamDataQualityConfig",
+ fields=[
+ (
+ "team",
+ models.OneToOneField(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ primary_key=True,
+ serialize=False,
+ to="posthog.team",
+ ),
+ ),
+ (
+ "gate_materialization_on_checks",
+ models.BooleanField(
+ default=False,
+ help_text="When true, a materialization whose error-severity checks fail is not published.",
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="DataQualityCheck",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ ("deleted", models.BooleanField(blank=True, default=False, null=True)),
+ ("deleted_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "name",
+ models.CharField(
+ blank=True,
+ help_text="Optional identifier-safe handle, unique per team when set. Blank means address the check by id.",
+ max_length=128,
+ validators=[
+ django.core.validators.RegexValidator(
+ message="Name must start with a letter and contain only letters, numbers, and underscores.",
+ regex="^[A-Za-z][A-Za-z0-9_]*$",
+ )
+ ],
+ ),
+ ),
+ (
+ "description",
+ models.TextField(
+ blank=True,
+ help_text="Why this check exists and what a failure means.",
+ ),
+ ),
+ (
+ "subject_type",
+ models.CharField(
+ choices=[("table", "table"), ("view", "view")],
+ help_text="Kind of catalog object being checked: table or view. Kept so orphaned checks stay readable.",
+ max_length=32,
+ ),
+ ),
+ (
+ "subject_name",
+ models.CharField(
+ help_text="Queryable name of the subject, refreshed on every run so renames self-heal.",
+ max_length=400,
+ ),
+ ),
+ (
+ "subject_status",
+ models.CharField(
+ choices=[("active", "active"), ("orphaned", "orphaned")],
+ default=products.data_quality.backend.facade.enums.SubjectStatus["ACTIVE"],
+ help_text="orphaned once the subject stops resolving; orphaned checks are skipped, not deleted.",
+ max_length=32,
+ ),
+ ),
+ (
+ "column_name",
+ models.CharField(
+ blank=True,
+ help_text="Column the check applies to. Blank for table-scoped types like row_count.",
+ max_length=400,
+ ),
+ ),
+ (
+ "check_type",
+ models.CharField(
+ help_text="Which assertion to make. Determines the shape of config.",
+ max_length=32,
+ ),
+ ),
+ (
+ "config",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ help_text="Type-specific configuration, validated against the check type's JSON schema.",
+ ),
+ ),
+ (
+ "severity",
+ models.CharField(
+ choices=[("error", "error"), ("warn", "warn")],
+ default=products.data_quality.backend.facade.enums.CheckSeverity["ERROR"],
+ help_text="error failures mark the subject failing and notify; warn failures only surface.",
+ max_length=16,
+ ),
+ ),
+ (
+ "enabled",
+ models.BooleanField(
+ default=True,
+ help_text="Disabled checks are never run by any trigger.",
+ ),
+ ),
+ (
+ "tags",
+ models.JSONField(
+ blank=True,
+ default=list,
+ help_text="Free-form labels for grouping and filtering.",
+ ),
+ ),
+ (
+ "last_run_at",
+ models.DateTimeField(blank=True, help_text="When the check last executed.", null=True),
+ ),
+ (
+ "last_status",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("passed", "passed"),
+ ("failed", "failed"),
+ ("errored", "errored"),
+ ("skipped", "skipped"),
+ ],
+ help_text="Outcome of the newest run, denormalized so health rollups stay a single read.",
+ max_length=16,
+ ),
+ ),
+ (
+ "fingerprint",
+ models.CharField(
+ help_text="sha256 of the canonical subject + type + column + config. The idempotency key for authoring.",
+ max_length=64,
+ ),
+ ),
+ (
+ "created_source",
+ models.CharField(
+ choices=[("user", "user"), ("ai_generated", "ai_generated")],
+ default=products.data_quality.backend.facade.enums.CreatedSource["USER"],
+ help_text="Whether a human or an agent authored this check.",
+ max_length=32,
+ ),
+ ),
+ (
+ "ai_model",
+ models.CharField(
+ blank=True,
+ help_text="Model that generated the check, if AI-authored.",
+ max_length=128,
+ ),
+ ),
+ (
+ "confidence",
+ models.FloatField(
+ blank=True,
+ help_text="AI author's confidence in the check, 0-1.",
+ null=True,
+ ),
+ ),
+ (
+ "reasoning",
+ models.TextField(
+ blank=True,
+ help_text="AI author's reasoning, surfaced as review context.",
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "owner",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ help_text="The human accountable for this check. AI generates, a human owns.",
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "saved_query",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ help_text="The view or matview this check audits. Exclusive with table.",
+ null=True,
+ on_delete=products.data_quality.backend.models.check.orphan_check_on_subject_delete,
+ related_name="+",
+ to="data_modeling.datawarehousesavedquery",
+ ),
+ ),
+ (
+ "table",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ help_text="The warehouse source table this check audits. Exclusive with saved_query.",
+ null=True,
+ on_delete=products.data_quality.backend.models.check.orphan_check_on_subject_delete,
+ related_name="+",
+ to="warehouse_sources.datawarehousetable",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="DataQualitySuiteRun",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "trigger",
+ models.CharField(
+ choices=[
+ ("manual", "manual"),
+ ("materialization", "materialization"),
+ ("source_sync", "source_sync"),
+ ],
+ help_text="What started this run: manual, materialization, or source_sync.",
+ max_length=32,
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("running", "running"),
+ ("completed", "completed"),
+ ("failed", "failed"),
+ ("empty", "empty"),
+ ],
+ default=products.data_quality.backend.facade.enums.SuiteRunStatus["RUNNING"],
+ help_text="empty means the trigger matched no runnable checks, which is not a failure.",
+ max_length=16,
+ ),
+ ),
+ (
+ "subject_type",
+ models.CharField(
+ blank=True,
+ choices=[("table", "table"), ("view", "view")],
+ help_text="Set when the run targets exactly one subject.",
+ max_length=32,
+ ),
+ ),
+ (
+ "subject_uuid",
+ models.UUIDField(
+ blank=True,
+ help_text="Set when the run targets exactly one subject.",
+ null=True,
+ ),
+ ),
+ ("workflow_id", models.CharField(blank=True, max_length=400)),
+ ("workflow_run_id", models.CharField(blank=True, max_length=400)),
+ (
+ "data_modeling_job_id",
+ models.UUIDField(
+ blank=True,
+ help_text="The materialization job that triggered this run, if any.",
+ null=True,
+ ),
+ ),
+ ("checks_passed", models.IntegerField(default=0)),
+ ("checks_failed", models.IntegerField(default=0)),
+ ("checks_errored", models.IntegerField(default=0)),
+ ("checks_skipped", models.IntegerField(default=0)),
+ ("started_at", models.DateTimeField(blank=True, null=True)),
+ ("finished_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "error",
+ models.TextField(
+ blank=True,
+ help_text="Why the suite itself failed, as opposed to an individual check.",
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="DataQualityCheckRun",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "subject_type",
+ models.CharField(choices=[("table", "table"), ("view", "view")], max_length=32),
+ ),
+ ("subject_uuid", models.UUIDField()),
+ ("subject_name", models.CharField(max_length=400)),
+ ("check_type", models.CharField(max_length=32)),
+ ("check_fingerprint", models.CharField(max_length=64)),
+ ("column_name", models.CharField(blank=True, max_length=400)),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("passed", "passed"),
+ ("failed", "failed"),
+ ("errored", "errored"),
+ ("skipped", "skipped"),
+ ],
+ max_length=16,
+ ),
+ ),
+ (
+ "failed_row_count",
+ models.BigIntegerField(
+ blank=True,
+ help_text="Rows violating the assertion. 0 is a pass.",
+ null=True,
+ ),
+ ),
+ (
+ "observed_value",
+ models.FloatField(
+ blank=True,
+ help_text="The check's headline number (row count, staleness in seconds, ...), kept as a time series.",
+ null=True,
+ ),
+ ),
+ (
+ "compiled_query",
+ models.TextField(
+ blank=True,
+ help_text="HogQL selecting the failing rows. Re-run it to see them. Cleared by retention after 30 days.",
+ ),
+ ),
+ (
+ "error",
+ models.TextField(
+ blank=True,
+ help_text="Compilation or execution failure, for status=errored.",
+ ),
+ ),
+ ("duration_ms", models.IntegerField(blank=True, null=True)),
+ ("started_at", models.DateTimeField(blank=True, null=True)),
+ ("finished_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "quality_check",
+ models.ForeignKey(
+ blank=True,
+ help_text="The definition executed. Nulled rather than cascaded so history outlives hard deletes.",
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="runs",
+ to="data_quality.dataqualitycheck",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ (
+ "suite_run",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="check_runs",
+ to="data_quality.dataqualitysuiterun",
+ ),
+ ),
+ ],
+ ),
+ migrations.AddIndex(
+ model_name="dataqualitycheck",
+ index=models.Index(
+ condition=models.Q(("saved_query__isnull", False)),
+ fields=["team", "saved_query"],
+ name="quality_check_saved_query_idx",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="dataqualitycheck",
+ index=models.Index(
+ condition=models.Q(("table__isnull", False)),
+ fields=["team", "table"],
+ name="quality_check_table_idx",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="dataqualitycheck",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ models.Q(
+ ("saved_query__isnull", False),
+ ("table__isnull", False),
+ _negated=True,
+ ),
+ models.Q(
+ ("saved_query__isnull", False),
+ (
+ "subject_type",
+ products.data_quality.backend.facade.enums.SubjectType["TABLE"],
+ ),
+ _negated=True,
+ ),
+ models.Q(
+ (
+ "subject_type",
+ products.data_quality.backend.facade.enums.SubjectType["VIEW"],
+ ),
+ ("table__isnull", False),
+ _negated=True,
+ ),
+ ),
+ name="quality_check_subject_binding",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="dataqualitycheck",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("saved_query__isnull", False)),
+ fields=("team", "saved_query", "fingerprint"),
+ name="unique_quality_check_fp_view",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="dataqualitycheck",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("table__isnull", False)),
+ fields=("team", "table", "fingerprint"),
+ name="unique_quality_check_fp_table",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="dataqualitycheck",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("name", ""), _negated=True),
+ fields=("team", "name"),
+ name="unique_quality_check_name_per_team",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="dataqualitysuiterun",
+ index=models.Index(fields=["team", "-created_at"], name="data_qualit_team_id_8a05dd_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="dataqualitysuiterun",
+ index=models.Index(
+ fields=["team", "subject_type", "subject_uuid"],
+ name="data_qualit_team_id_e9c621_idx",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="dataqualitycheckrun",
+ index=models.Index(
+ fields=["quality_check", "-created_at"],
+ name="data_qualit_quality_6f718b_idx",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="dataqualitycheckrun",
+ index=models.Index(fields=["team", "created_at"], name="data_qualit_team_id_0f3f54_idx"),
+ ),
+ ]
diff --git a/products/data_quality/backend/migrations/__init__.py b/products/data_quality/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/data_quality/backend/migrations/max_migration.txt b/products/data_quality/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..cbab66dde92a
--- /dev/null
+++ b/products/data_quality/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_initial
diff --git a/products/data_quality/backend/models/__init__.py b/products/data_quality/backend/models/__init__.py
new file mode 100644
index 000000000000..0c46334fa2d7
--- /dev/null
+++ b/products/data_quality/backend/models/__init__.py
@@ -0,0 +1,11 @@
+from .check import CHECK_NAME_REGEX, DataQualityCheck
+from .check_run import DataQualityCheckRun, DataQualitySuiteRun
+from .team_data_quality_config import TeamDataQualityConfig
+
+__all__ = [
+ "CHECK_NAME_REGEX",
+ "DataQualityCheck",
+ "DataQualityCheckRun",
+ "DataQualitySuiteRun",
+ "TeamDataQualityConfig",
+]
diff --git a/products/data_quality/backend/models/check.py b/products/data_quality/backend/models/check.py
new file mode 100644
index 000000000000..aa10af6333fb
--- /dev/null
+++ b/products/data_quality/backend/models/check.py
@@ -0,0 +1,229 @@
+import uuid
+from typing import Any, cast
+
+from django.core.validators import RegexValidator
+from django.db import models
+from django.db.models.deletion import Collector
+
+from posthog.models.activity_logging.model_activity import ModelActivityMixin
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDModel
+
+from ..facade.enums import CheckRunStatus, CheckSeverity, CreatedSource, SubjectStatus, SubjectType
+
+# A check name is an addressable handle in `information_schema.data_quality_checks` and in agent
+# prose, so it follows the same bare-identifier discipline as a metric name.
+CHECK_NAME_REGEX = r"^[A-Za-z][A-Za-z0-9_]*$"
+
+SUBJECT_STATUS_FIELD = "subject_status"
+
+validate_check_name = RegexValidator(
+ regex=CHECK_NAME_REGEX,
+ message="Name must start with a letter and contain only letters, numbers, and underscores.",
+)
+
+
+def orphan_check_on_subject_delete(collector: Collector, field: models.ForeignKey, sub_objs: Any, using: str) -> None:
+ """Unbind the check and mark it orphaned in the same delete, instead of a plain ``SET_NULL``.
+
+ Nulling the key alone leaves the row reading ``active`` with no subject, and nothing would ever
+ correct it: checks run when their subject's data changes, and a deleted subject never changes
+ again.
+
+ The status update is queued first on purpose. The collector runs its field updates in insertion
+ order against the same queryset, which filters on the key this handler is about to null -- queued
+ second, it would match no rows.
+
+ ``sub_objs`` is the lazy queryset ``lazy_sub_objs`` asks for, which django-stubs types as an
+ indexable collection.
+ """
+ status_field = cast(models.Field, field.model._meta.get_field(SUBJECT_STATUS_FIELD))
+ collector.add_field_update(status_field, SubjectStatus.ORPHANED.value, sub_objs)
+ collector.add_field_update(field, None, sub_objs)
+
+
+orphan_check_on_subject_delete.lazy_sub_objs = True # type: ignore[attr-defined]
+
+
+class DataQualityCheck(
+ ModelActivityMixin, TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, DeletedMetaFields, UUIDModel
+):
+ """An assertion about a warehouse table or view, in the ``dbt test`` sense.
+
+ A check passes when its compiled query finds zero failing rows. The definition is the source of
+ truth here; ``fingerprint`` makes agent authoring idempotent (re-creating a semantically
+ identical check upserts instead of duplicating), and it is also the stable identity a git-synced
+ config file would round-trip against.
+
+ The subject is one of two foreign keys -- ``saved_query`` (views and matviews) or ``table``
+ (warehouse source tables) -- and never both. The data modeling Node for a subject is resolved at
+ trigger time rather than referenced here: node rows are per-DAG structural records that DAG sync
+ deletes and recreates, so they cannot anchor a check's identity, and a table in no DAG has no
+ node at all. A hard-deleted subject nulls its FK (the check turns ``orphaned`` and is skipped);
+ orphaned checks fall outside the partial fingerprint constraints, so duplicate-fingerprint
+ orphans are possible and harmless.
+
+ ``last_status`` / ``last_run_at`` are denormalized from the newest ``DataQualityCheckRun`` so
+ per-subject health is a single indexed read rather than a correlated subquery over run history.
+
+ Checks carry no cadence: they run when their subject's data changes (a sync completes, a
+ materialization runs) or on demand, never on a timer of their own.
+ """
+
+ # db_constraint=False on FKs to hot tables (posthog_team, posthog_user): a real FK constraint
+ # takes SHARE ROW EXCLUSIVE on the parent, stalling writes under traffic. Scoping/integrity is
+ # enforced at the app layer.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+"
+ )
+ owner = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ help_text="The human accountable for this check. AI generates, a human owns.",
+ )
+
+ name = models.CharField(
+ max_length=128,
+ blank=True,
+ validators=[validate_check_name],
+ help_text="Optional identifier-safe handle, unique per team when set. Blank means address the check by id.",
+ )
+ description = models.TextField(blank=True, help_text="Why this check exists and what a failure means.")
+
+ subject_type = models.CharField(
+ max_length=32,
+ choices=[(t.value, t.value) for t in SubjectType],
+ help_text="Kind of catalog object being checked: table or view. Kept so orphaned checks stay readable.",
+ )
+ saved_query = models.ForeignKey(
+ "data_modeling.DataWarehouseSavedQuery",
+ on_delete=orphan_check_on_subject_delete,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ help_text="The view or matview this check audits. Exclusive with table.",
+ )
+ table = models.ForeignKey(
+ "warehouse_sources.DataWarehouseTable",
+ on_delete=orphan_check_on_subject_delete,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ help_text="The warehouse source table this check audits. Exclusive with saved_query.",
+ )
+ subject_name = models.CharField(
+ max_length=400,
+ help_text="Queryable name of the subject, refreshed on every run so renames self-heal.",
+ )
+ subject_status = models.CharField(
+ max_length=32,
+ choices=[(s.value, s.value) for s in SubjectStatus],
+ default=SubjectStatus.ACTIVE,
+ help_text="orphaned once the subject stops resolving; orphaned checks are skipped, not deleted.",
+ )
+ column_name = models.CharField(
+ max_length=400,
+ blank=True,
+ help_text="Column the check applies to. Blank for table-scoped types like row_count.",
+ )
+
+ # No choices: the check registry is the source of truth for which types exist, and Django
+ # serializes choices into migration state -- adding a type would then need a migration.
+ check_type = models.CharField(
+ max_length=32,
+ help_text="Which assertion to make. Determines the shape of config.",
+ )
+ config = models.JSONField(
+ default=dict,
+ blank=True,
+ help_text="Type-specific configuration, validated against the check type's JSON schema.",
+ )
+ severity = models.CharField(
+ max_length=16,
+ choices=[(s.value, s.value) for s in CheckSeverity],
+ default=CheckSeverity.ERROR,
+ help_text="error failures mark the subject failing and notify; warn failures only surface.",
+ )
+ enabled = models.BooleanField(default=True, help_text="Disabled checks are never run by any trigger.")
+ tags = models.JSONField(default=list, blank=True, help_text="Free-form labels for grouping and filtering.")
+
+ last_run_at = models.DateTimeField(null=True, blank=True, help_text="When the check last executed.")
+ last_status = models.CharField(
+ max_length=16,
+ choices=[(s.value, s.value) for s in CheckRunStatus],
+ blank=True,
+ help_text="Outcome of the newest run, denormalized so health rollups stay a single read.",
+ )
+
+ fingerprint = models.CharField(
+ max_length=64,
+ help_text="sha256 of the canonical subject + type + column + config. The idempotency key for authoring.",
+ )
+
+ created_source = models.CharField(
+ max_length=32,
+ choices=[(s.value, s.value) for s in CreatedSource],
+ default=CreatedSource.USER,
+ help_text="Whether a human or an agent authored this check.",
+ )
+ ai_model = models.CharField(max_length=128, blank=True, help_text="Model that generated the check, if AI-authored.")
+ confidence = models.FloatField(null=True, blank=True, help_text="AI author's confidence in the check, 0-1.")
+ reasoning = models.TextField(blank=True, help_text="AI author's reasoning, surfaced as review context.")
+
+ class Meta:
+ constraints = [
+ # The subject invariant: at most one FK set, and subject_type must match the FK that is.
+ # Both FKs null is the orphaned state.
+ models.CheckConstraint(
+ name="quality_check_subject_binding",
+ condition=(
+ ~models.Q(saved_query__isnull=False, table__isnull=False)
+ & ~models.Q(saved_query__isnull=False, subject_type=SubjectType.TABLE)
+ & ~models.Q(table__isnull=False, subject_type=SubjectType.VIEW)
+ ),
+ ),
+ # Partial per FK: orphaned checks (both FKs null) are exempt on purpose.
+ models.UniqueConstraint(
+ fields=["team", "saved_query", "fingerprint"],
+ condition=models.Q(saved_query__isnull=False),
+ name="unique_quality_check_fp_view",
+ ),
+ models.UniqueConstraint(
+ fields=["team", "table", "fingerprint"],
+ condition=models.Q(table__isnull=False),
+ name="unique_quality_check_fp_table",
+ ),
+ # Partial: a blank name is the "address me by id" case, and many checks share it.
+ models.UniqueConstraint(
+ fields=["team", "name"],
+ condition=~models.Q(name=""),
+ name="unique_quality_check_name_per_team",
+ ),
+ ]
+ indexes = [
+ models.Index(
+ fields=["team", "saved_query"],
+ condition=models.Q(saved_query__isnull=False),
+ name="quality_check_saved_query_idx",
+ ),
+ models.Index(
+ fields=["team", "table"],
+ condition=models.Q(table__isnull=False),
+ name="quality_check_table_idx",
+ ),
+ ]
+
+ @property
+ def subject_uuid(self) -> "uuid.UUID | None":
+ """Id of whichever subject FK is set; None once orphaned."""
+ return self.saved_query_id or self.table_id
+
+ def __str__(self) -> str:
+ return self.name or f"{self.check_type} on {self.subject_name}"
diff --git a/products/data_quality/backend/models/check_run.py b/products/data_quality/backend/models/check_run.py
new file mode 100644
index 000000000000..fc080776333d
--- /dev/null
+++ b/products/data_quality/backend/models/check_run.py
@@ -0,0 +1,134 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
+
+from ..facade.enums import CheckRunStatus, SubjectType, SuiteRunStatus, SuiteRunTrigger
+
+
+class DataQualitySuiteRun(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):
+ """One batch of check executions, and the handle an API caller polls for a report.
+
+ A suite is scoped to whatever the trigger asked for -- a single subject, an explicit set of
+ checks, or every check on the models a DAG run just materialized -- so the optional subject
+ columns are a convenience for the common single-subject case, not the run's identity.
+ """
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+"
+ )
+
+ trigger = models.CharField(
+ max_length=32,
+ choices=[(t.value, t.value) for t in SuiteRunTrigger],
+ help_text="What started this run: manual, materialization, or source_sync.",
+ )
+ status = models.CharField(
+ max_length=16,
+ choices=[(s.value, s.value) for s in SuiteRunStatus],
+ default=SuiteRunStatus.RUNNING,
+ help_text="empty means the trigger matched no runnable checks, which is not a failure.",
+ )
+
+ subject_type = models.CharField(
+ max_length=32,
+ choices=[(t.value, t.value) for t in SubjectType],
+ blank=True,
+ help_text="Set when the run targets exactly one subject.",
+ )
+ subject_uuid = models.UUIDField(null=True, blank=True, help_text="Set when the run targets exactly one subject.")
+
+ workflow_id = models.CharField(max_length=400, blank=True)
+ workflow_run_id = models.CharField(max_length=400, blank=True)
+ # Loose reference, not an FK: DataModelingJob is another product's model.
+ data_modeling_job_id = models.UUIDField(
+ null=True, blank=True, help_text="The materialization job that triggered this run, if any."
+ )
+
+ checks_passed = models.IntegerField(default=0)
+ checks_failed = models.IntegerField(default=0)
+ checks_errored = models.IntegerField(default=0)
+ checks_skipped = models.IntegerField(default=0)
+
+ started_at = models.DateTimeField(null=True, blank=True)
+ finished_at = models.DateTimeField(null=True, blank=True)
+ error = models.TextField(blank=True, help_text="Why the suite itself failed, as opposed to an individual check.")
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["team", "-created_at"]),
+ models.Index(fields=["team", "subject_type", "subject_uuid"]),
+ ]
+
+ def __str__(self) -> str:
+ return f"suite run {self.id} ({self.status})"
+
+
+class DataQualityCheckRun(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):
+ """One execution of one check.
+
+ Deliberately stores counts and the compiled query, never failing rows -- warehouse data can be
+ sensitive and this table lives in the main Postgres. To see the offending rows, re-run
+ ``compiled_query``.
+
+ ``observed_value`` is recorded on passes too, not just failures: the resulting numeric time
+ series is what future anomaly-detection check types train on.
+ """
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+"
+ )
+ # Named quality_check, never check: Django reserves Model.check() and a field called `check`
+ # shadows it (models.E020).
+ quality_check = models.ForeignKey(
+ "data_quality.DataQualityCheck",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="runs",
+ help_text="The definition executed. Nulled rather than cascaded so history outlives hard deletes.",
+ )
+ suite_run = models.ForeignKey(
+ "data_quality.DataQualitySuiteRun",
+ on_delete=models.CASCADE,
+ related_name="check_runs",
+ )
+
+ # Denormalized from the check so history stays readable after the definition changes or goes away.
+ subject_type = models.CharField(max_length=32, choices=[(t.value, t.value) for t in SubjectType])
+ subject_uuid = models.UUIDField()
+ subject_name = models.CharField(max_length=400)
+ # No choices, for the same reason as on the check itself: the registry owns the set of types.
+ check_type = models.CharField(max_length=32)
+ check_fingerprint = models.CharField(max_length=64)
+ column_name = models.CharField(max_length=400, blank=True)
+
+ status = models.CharField(max_length=16, choices=[(s.value, s.value) for s in CheckRunStatus])
+ failed_row_count = models.BigIntegerField(
+ null=True, blank=True, help_text="Rows violating the assertion. 0 is a pass."
+ )
+ observed_value = models.FloatField(
+ null=True,
+ blank=True,
+ help_text="The check's headline number (row count, staleness in seconds, ...), kept as a time series.",
+ )
+ compiled_query = models.TextField(
+ blank=True,
+ help_text="HogQL selecting the failing rows. Re-run it to see them. Cleared by retention after 30 days.",
+ )
+ error = models.TextField(blank=True, help_text="Compilation or execution failure, for status=errored.")
+ duration_ms = models.IntegerField(null=True, blank=True)
+
+ started_at = models.DateTimeField(null=True, blank=True)
+ finished_at = models.DateTimeField(null=True, blank=True)
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["quality_check", "-created_at"]),
+ models.Index(fields=["team", "created_at"]),
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.check_type} on {self.subject_name}: {self.status}"
diff --git a/products/data_quality/backend/models/team_data_quality_config.py b/products/data_quality/backend/models/team_data_quality_config.py
new file mode 100644
index 000000000000..cc2dad100705
--- /dev/null
+++ b/products/data_quality/backend/models/team_data_quality_config.py
@@ -0,0 +1,31 @@
+import logging
+
+from django.db import models
+
+from posthog.models.team import Team
+from posthog.models.team.extensions import register_team_extension_signal
+
+logger = logging.getLogger(__name__)
+
+
+class TeamDataQualityConfig(models.Model):
+ """Per-team data quality settings, as a Team extension (posthog_team is never ALTERed).
+
+ Warning behavior is unconditional -- checks always run and surface health. The gate only decides
+ whether a blocking failure stops a materialization from publishing.
+ """
+
+ # db_constraint=False: a real FK constraint takes SHARE ROW EXCLUSIVE on posthog_team while
+ # migrating, stalling writes under traffic.
+ team = models.OneToOneField(Team, on_delete=models.CASCADE, primary_key=True, db_constraint=False)
+
+ gate_materialization_on_checks = models.BooleanField(
+ default=False,
+ help_text="When true, a materialization whose error-severity checks fail is not published.",
+ )
+
+ class Meta:
+ app_label = "data_quality"
+
+
+register_team_extension_signal(TeamDataQualityConfig, logger=logger)
diff --git a/products/data_quality/backend/tests/__init__.py b/products/data_quality/backend/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/data_quality/backend/tests/test_compiler.py b/products/data_quality/backend/tests/test_compiler.py
new file mode 100644
index 000000000000..5825efaee4fa
--- /dev/null
+++ b/products/data_quality/backend/tests/test_compiler.py
@@ -0,0 +1,278 @@
+import pytest
+
+from parameterized import parameterized
+
+from products.data_quality.backend.facade.enums import CheckType, SubjectType
+from products.data_quality.backend.logic.compiler import compile_check
+from products.data_quality.backend.logic.contracts import Evaluation, SubjectRef
+from products.data_quality.backend.logic.errors import CheckConfigError, SubjectUnresolvableError
+from products.data_quality.backend.logic.registry import UnknownCheckTypeError, all_specs, get_spec
+from products.data_quality.backend.logic.serialization import compute_fingerprint, from_config_entry, to_config_entry
+from products.data_quality.backend.logic.spec import CheckTypeSpec, NoConfig
+
+ORDERS = SubjectRef(SubjectType.VIEW, "1cd4a1ef-0000-0000-0000-000000000001", "orders", "orders", exists=True)
+CUSTOMERS = SubjectRef(SubjectType.TABLE, "1cd4a1ef-0000-0000-0000-000000000002", "customers", "customers", True)
+
+RELATIONSHIPS_CONFIG = {
+ "to_subject_type": "table",
+ "to_subject_uuid": "1cd4a1ef-0000-0000-0000-000000000002",
+ "to_column": "id",
+}
+
+
+def _normalized(check_type, column_name, config) -> dict:
+ """What the fingerprint hashes: config put through its type's model first."""
+ return get_spec(check_type).validate(config, column_name).model_dump(mode="json")
+
+
+def _fingerprint_for(config: dict) -> str:
+ return compute_fingerprint(
+ subject_type=SubjectType.VIEW,
+ subject_uuid=ORDERS.subject_uuid,
+ check_type=CheckType.NOT_NULL,
+ column_name="customer_id",
+ config=config,
+ )
+
+
+def _compile(check_type, column_name, config, related=None):
+ return compile_check(
+ check_type=check_type,
+ subject=ORDERS,
+ column_name=column_name,
+ config=config,
+ related_subject=related,
+ )
+
+
+class TestCheckCompiler:
+ @parameterized.expand(
+ [
+ (
+ CheckType.NOT_NULL,
+ "customer_id",
+ {},
+ None,
+ "SELECT count() AS failure_count, count() AS observed_value "
+ "FROM (SELECT 1 FROM orders WHERE isNull(customer_id))",
+ ),
+ (
+ CheckType.UNIQUE,
+ "id",
+ {},
+ None,
+ "SELECT count() AS failure_count, count() AS observed_value "
+ "FROM (SELECT id FROM orders WHERE isNotNull(id) GROUP BY id HAVING greater(count(), 1))",
+ ),
+ (
+ CheckType.ACCEPTED_VALUES,
+ "status",
+ {"values": ["paid", "refunded"]},
+ None,
+ "SELECT count() AS failure_count, count() AS observed_value FROM (SELECT 1 FROM orders "
+ "WHERE and(isNotNull(status), notIn(status, ['paid', 'refunded'])))",
+ ),
+ (
+ CheckType.RELATIONSHIPS,
+ "customer_id",
+ RELATIONSHIPS_CONFIG,
+ CUSTOMERS,
+ "SELECT count() AS failure_count, count() AS observed_value FROM (SELECT 1 FROM orders "
+ "WHERE and(isNotNull(customer_id), notIn(customer_id, (SELECT id FROM customers))))",
+ ),
+ (
+ CheckType.ROW_COUNT,
+ "",
+ {"min": 1},
+ None,
+ "SELECT count() AS observed_value FROM (SELECT 1 FROM orders)",
+ ),
+ (
+ CheckType.FRESHNESS,
+ "created_at",
+ {"max_age_minutes": 60},
+ None,
+ "SELECT countIf(or(isNull(staleness_seconds), greater(staleness_seconds, 3600))) AS failure_count, "
+ "max(staleness_seconds) AS observed_value "
+ "FROM (SELECT dateDiff('second', max(created_at), now()) AS staleness_seconds FROM orders)",
+ ),
+ (
+ CheckType.CUSTOM_SQL,
+ "",
+ {"query": "select 1 from orders where total < 0"},
+ None,
+ "SELECT count() AS failure_count, count() AS observed_value "
+ "FROM (SELECT 1 FROM orders WHERE less(total, 0))",
+ ),
+ (
+ CheckType.CUSTOM_SQL,
+ "",
+ {"query": "select id from orders where total < 0 union all select id from orders where total > 100"},
+ None,
+ "SELECT count() AS failure_count, count() AS observed_value "
+ "FROM (SELECT id FROM orders WHERE less(total, 0) "
+ "UNION ALL SELECT id FROM orders WHERE greater(total, 100))",
+ ),
+ ]
+ )
+ def test_compiles_to_a_count_only_query(self, check_type, column_name, config, related, expected) -> None:
+ assert _compile(check_type, column_name, config, related).printed_query == expected
+
+ @parameterized.expand(
+ [
+ ("not_null", CheckType.NOT_NULL, "customer_id", {}, None, "SELECT * FROM orders WHERE isNull(customer_id)"),
+ (
+ "accepted_values",
+ CheckType.ACCEPTED_VALUES,
+ "status",
+ {"values": ["paid"]},
+ None,
+ "SELECT * FROM orders WHERE and(isNotNull(status), notIn(status, ['paid']))",
+ ),
+ (
+ "row_count",
+ CheckType.ROW_COUNT,
+ "",
+ {"min": 1},
+ None,
+ "SELECT count() AS row_count FROM orders",
+ ),
+ ]
+ )
+ def test_the_stored_query_shows_the_offending_data(
+ self, _name, check_type, column_name, config, related, expected
+ ) -> None:
+ # Failing rows are never persisted, so re-running this query is the only way a human can see
+ # what broke -- a constant projection would answer with a column of 1s.
+ assert _compile(check_type, column_name, config, related).printed_failing_rows_query == expected
+
+ def test_freshness_fails_when_the_column_has_no_values_at_all(self) -> None:
+ # An empty table or dead pipeline yields a null staleness; comparing null to the threshold
+ # would silently pass, which is the exact case freshness is meant to catch.
+ compiled = _compile(CheckType.FRESHNESS, "created_at", {"max_age_minutes": 60})
+
+ assert "isNull(staleness_seconds)" in compiled.printed_query
+
+ def test_row_count_is_the_only_type_not_using_zero_rows_pass(self) -> None:
+ assert _compile(CheckType.ROW_COUNT, "", {"min": 1}).evaluation is Evaluation.BOUNDS
+ assert _compile(CheckType.NOT_NULL, "id", {}).evaluation is Evaluation.ZERO_ROWS_PASS
+
+ @parameterized.expand(
+ [
+ ("backtick", "we`ird", "col", "`we``ird`"),
+ ("injection", "orders", 'foo"; DROP TABLE--', '`foo"; DROP TABLE--`'),
+ ("unicode", "orders", "コラム", "`コラム`"),
+ ]
+ )
+ def test_hostile_identifiers_are_escaped(self, _name, table, column_name, expected_fragment) -> None:
+ subject = SubjectRef(SubjectType.VIEW, ORDERS.subject_uuid, table, table, exists=True)
+ compiled = compile_check(check_type=CheckType.NOT_NULL, subject=subject, column_name=column_name, config={})
+ assert expected_fragment in compiled.printed_query
+
+ @parameterized.expand(
+ [
+ ("empty_accepted_values", CheckType.ACCEPTED_VALUES, "status", {"values": []}),
+ ("unknown_config_key", CheckType.NOT_NULL, "id", {"tolerance": 5}),
+ ("missing_column", CheckType.NOT_NULL, "", {}),
+ ("row_count_without_bounds", CheckType.ROW_COUNT, "", {}),
+ ("row_count_inverted_bounds", CheckType.ROW_COUNT, "", {"min": 10, "max": 1}),
+ ("custom_sql_not_a_select", CheckType.CUSTOM_SQL, "", {"query": "drop table orders"}),
+ (
+ "custom_sql_with_placeholder",
+ CheckType.CUSTOM_SQL,
+ "",
+ {"query": "select 1 from orders where {filters}"},
+ ),
+ ("freshness_without_threshold", CheckType.FRESHNESS, "created_at", {}),
+ ]
+ )
+ def test_invalid_config_is_rejected(self, _name, check_type, column_name, config) -> None:
+ with pytest.raises(CheckConfigError):
+ _compile(check_type, column_name, config)
+
+ def test_relationships_to_an_unresolvable_subject_is_rejected(self) -> None:
+ missing = SubjectRef(SubjectType.TABLE, CUSTOMERS.subject_uuid, "", "", exists=False)
+ with pytest.raises(SubjectUnresolvableError):
+ _compile(CheckType.RELATIONSHIPS, "customer_id", RELATIONSHIPS_CONFIG, missing)
+
+ def test_compiling_against_a_gone_subject_is_rejected(self) -> None:
+ gone = SubjectRef(SubjectType.VIEW, ORDERS.subject_uuid, "", "", exists=False)
+ with pytest.raises(SubjectUnresolvableError):
+ compile_check(check_type=CheckType.NOT_NULL, subject=gone, column_name="id", config={})
+
+ def test_unknown_check_type_names_the_supported_types(self) -> None:
+ with pytest.raises(UnknownCheckTypeError, match="not_null"):
+ _compile("anomaly", "id", {})
+
+ def test_every_check_type_has_a_spec(self) -> None:
+ assert {spec.type_name for spec in all_specs()} == set(CheckType)
+
+ def test_every_spec_publishes_a_generated_json_schema(self) -> None:
+ # The schema is what the check_types endpoint and the MCP tool docs hand to agents, and it
+ # is derived from the config model rather than written by hand, so it cannot drift from
+ # what parse_config actually accepts.
+ for spec in all_specs():
+ schema = spec.json_schema
+ assert schema["type"] == "object"
+ assert schema["additionalProperties"] is False, f"{spec.type_name} silently ignores unknown keys"
+
+ def test_a_spec_missing_part_of_the_contract_cannot_be_instantiated(self) -> None:
+ # An ABC rather than a Protocol so this fails here, not on the first agent to use it.
+ class Incomplete(CheckTypeSpec):
+ type_name = CheckType.NOT_NULL
+ config_model = NoConfig
+ requires_column = False
+ description = "no build method"
+
+ with pytest.raises(TypeError, match="build"):
+ Incomplete() # type: ignore[abstract]
+
+
+class TestCheckSerialization:
+ @parameterized.expand([(check_type,) for check_type in CheckType])
+ def test_config_entry_round_trips(self, check_type) -> None:
+ check = {
+ "name": "orders_check",
+ "description": "why it exists",
+ "subject_type": SubjectType.VIEW,
+ "subject_uuid": ORDERS.subject_uuid,
+ "column_name": "customer_id",
+ "check_type": check_type,
+ "config": {"values": ["a"], "max_age_minutes": 60},
+ "severity": "warn",
+ "enabled": False,
+ "tags": ["finance"],
+ }
+ entry = to_config_entry(check)
+ assert to_config_entry(from_config_entry(entry)) == entry
+
+ def test_fingerprint_changes_when_the_assertion_changes(self) -> None:
+ def fingerprint(column_name: str, values: list[str]) -> str:
+ return compute_fingerprint(
+ subject_type=SubjectType.VIEW,
+ subject_uuid=ORDERS.subject_uuid,
+ check_type=CheckType.ACCEPTED_VALUES,
+ column_name=column_name,
+ config=_normalized(CheckType.ACCEPTED_VALUES, column_name, {"values": values}),
+ )
+
+ assert fingerprint("status", ["paid", "refunded"]) != fingerprint("status", ["paid"])
+ assert fingerprint("status", ["paid", "refunded"]) != fingerprint("total", ["paid", "refunded"])
+
+ def test_accepted_values_fingerprint_ignores_order_and_duplicates(self) -> None:
+ # accepted_values is a set: reordering or repeating a value must not create a twin check that
+ # slips past the fingerprint uniqueness constraint.
+ canonical = _normalized(CheckType.ACCEPTED_VALUES, "status", {"values": ["paid", "refunded"]})
+ shuffled = _normalized(CheckType.ACCEPTED_VALUES, "status", {"values": ["refunded", "paid", "paid"]})
+
+ assert canonical == shuffled
+ assert _fingerprint_for(canonical) == _fingerprint_for(shuffled)
+
+ def test_configs_that_differ_only_in_json_type_share_a_fingerprint(self) -> None:
+ # Normalizing through the type's model first is what makes this hold: an agent sending
+ # max_age_minutes as "60" must upsert the check it already created with 60, not add a twin.
+ as_int = _normalized(CheckType.FRESHNESS, "created_at", {"max_age_minutes": 60})
+ as_string = _normalized(CheckType.FRESHNESS, "created_at", {"max_age_minutes": "60"})
+
+ assert as_int == as_string
+ assert _fingerprint_for(as_int) == _fingerprint_for(as_string)
diff --git a/products/data_quality/backend/tests/test_compiler_execution.py b/products/data_quality/backend/tests/test_compiler_execution.py
new file mode 100644
index 000000000000..9b0b176c56b8
--- /dev/null
+++ b/products/data_quality/backend/tests/test_compiler_execution.py
@@ -0,0 +1,200 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from parameterized import parameterized
+
+from posthog.hogql.query import execute_hogql_query
+
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.data_quality.backend.facade.enums import CheckType, SubjectType
+from products.data_quality.backend.logic.compiler import compile_check
+from products.data_quality.backend.logic.contracts import CompiledCheck, SubjectRef
+
+_STRING = {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)"}
+_INT = {"hogql": "IntegerDatabaseField", "clickhouse": "Int64"}
+_DATETIME = {"hogql": "DateTimeDatabaseField", "clickhouse": "Nullable(DateTime)"}
+
+# id | customer_id | status: one null customer_id, a duplicate id, a status outside the allowed set,
+# and a customer_id (c9) with no matching customer -- so every assertion below has a known count.
+_ORDERS_QUERY = (
+ "SELECT 1 AS id, 'c1' AS customer_id, 'paid' AS status "
+ "UNION ALL SELECT 2, 'c2', 'refunded' "
+ "UNION ALL SELECT 3, nullIf('', ''), 'paid' "
+ "UNION ALL SELECT 3, 'c9', 'shipped'"
+)
+
+_NULL_CUSTOMER_ROW = {"id": 3, "customer_id": None, "status": "paid"}
+_UNMATCHED_CUSTOMER_ROW = {"id": 3, "customer_id": "c9", "status": "shipped"}
+
+
+class TestCompiledCheckExecution(ClickhouseTestMixin, APIBaseTest):
+ """Compiled checks must run in ClickHouse and count what the data actually contains.
+
+ Views of constant rows, so the expected counts are exact and nothing has to be ingested. This
+ catches a query that prints but errors in ClickHouse, or returns the wrong number, neither of
+ which the printed-shape assertions in test_compiler can see.
+ """
+
+ def setUp(self) -> None:
+ super().setUp()
+ self._subjects: dict[str, SubjectRef] = {}
+ self._view("orders", _ORDERS_QUERY, {"id": _INT, "customer_id": _STRING, "status": _STRING})
+ self._view("customers", "SELECT 'c1' AS id UNION ALL SELECT 'c2'", {"id": _STRING})
+ self._view("all_customers", "SELECT 'c1' AS id UNION ALL SELECT 'c2' UNION ALL SELECT 'c9'", {"id": _STRING})
+ self._view("fresh_orders", "SELECT now() AS created_at", {"created_at": _DATETIME})
+ self._view("stale_orders", "SELECT toDateTime('2000-01-01 00:00:00') AS created_at", {"created_at": _DATETIME})
+ self._view("empty_orders", "SELECT now() AS created_at LIMIT 0", {"created_at": _DATETIME})
+ self._view(
+ "null_ts_orders",
+ "SELECT nullIf(now(), now()) AS created_at UNION ALL SELECT nullIf(now(), now())",
+ {"created_at": _DATETIME},
+ )
+
+ def _view(self, name: str, query: str, columns: dict[str, Any]) -> None:
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ team=self.team, name=name, query={"kind": "HogQLQuery", "query": query}, columns=columns
+ )
+ self._subjects[name] = SubjectRef(SubjectType.VIEW, str(saved_query.id), name, name, exists=True)
+
+ def _compile(self, view_name, check_type, column_name, config, related_view=None) -> CompiledCheck:
+ return compile_check(
+ check_type=check_type,
+ subject=self._subjects[view_name],
+ column_name=column_name,
+ config=config,
+ related_subject=self._subjects[related_view] if related_view else None,
+ )
+
+ def _execute(self, query) -> Any:
+ return execute_hogql_query(
+ query=query,
+ team=self.team,
+ query_type="data_quality_check",
+ bypass_warehouse_access_control=True,
+ )
+
+ def _relationships_config(self) -> dict:
+ return {
+ "to_subject_type": "view",
+ "to_subject_uuid": self._subjects["customers"].subject_uuid,
+ "to_column": "id",
+ }
+
+ @parameterized.expand(
+ [
+ ("not_null_pass", "orders", CheckType.NOT_NULL, "status", {}, None, 0),
+ ("not_null_fail", "orders", CheckType.NOT_NULL, "customer_id", {}, None, 1),
+ ("unique_pass", "orders", CheckType.UNIQUE, "customer_id", {}, None, 0),
+ ("unique_fail", "orders", CheckType.UNIQUE, "id", {}, None, 1),
+ (
+ "accepted_values_pass",
+ "orders",
+ CheckType.ACCEPTED_VALUES,
+ "status",
+ {"values": ["paid", "refunded", "shipped"]},
+ None,
+ 0,
+ ),
+ (
+ "accepted_values_fail",
+ "orders",
+ CheckType.ACCEPTED_VALUES,
+ "status",
+ {"values": ["paid", "refunded"]},
+ None,
+ 1,
+ ),
+ ("relationships_pass", "orders", CheckType.RELATIONSHIPS, "customer_id", None, "all_customers", 0),
+ ("relationships_fail", "orders", CheckType.RELATIONSHIPS, "customer_id", None, "customers", 1),
+ (
+ "custom_sql_pass",
+ "orders",
+ CheckType.CUSTOM_SQL,
+ "",
+ {"query": "SELECT id FROM orders WHERE id < 0"},
+ None,
+ 0,
+ ),
+ (
+ "custom_sql_fail",
+ "orders",
+ CheckType.CUSTOM_SQL,
+ "",
+ {"query": "SELECT id FROM orders WHERE customer_id IS NULL"},
+ None,
+ 1,
+ ),
+ ("freshness_pass", "fresh_orders", CheckType.FRESHNESS, "created_at", {"max_age_minutes": 60}, None, 0),
+ (
+ "freshness_stale_fail",
+ "stale_orders",
+ CheckType.FRESHNESS,
+ "created_at",
+ {"max_age_minutes": 60},
+ None,
+ 1,
+ ),
+ # An empty table and an all-null column both leave the newest timestamp undefined. Freshness
+ # has to fail there: comparing null to the threshold would pass the dead pipeline it exists
+ # to catch.
+ (
+ "freshness_empty_fail",
+ "empty_orders",
+ CheckType.FRESHNESS,
+ "created_at",
+ {"max_age_minutes": 60},
+ None,
+ 1,
+ ),
+ (
+ "freshness_all_null_fail",
+ "null_ts_orders",
+ CheckType.FRESHNESS,
+ "created_at",
+ {"max_age_minutes": 60},
+ None,
+ 1,
+ ),
+ ]
+ )
+ def test_failure_count_matches_the_data(
+ self, _name, view_name, check_type, column_name, config, related_view, expected_failure_count
+ ) -> None:
+ merged_config = config if config is not None else self._relationships_config()
+ compiled = self._compile(view_name, check_type, column_name, merged_config, related_view)
+
+ assert self._execute(compiled.query).results[0][0] == expected_failure_count
+
+ def test_row_count_observes_the_true_count(self) -> None:
+ # row_count is the one BOUNDS check: it emits only observed_value, and the bound comparison is
+ # the runner's job. What has to be right here is that the count it hands the runner is real.
+ compiled = self._compile("orders", CheckType.ROW_COUNT, "", {"min": 1, "max": 10})
+
+ assert self._execute(compiled.query).results[0][0] == 4
+
+ @parameterized.expand(
+ [
+ ("not_null", CheckType.NOT_NULL, "customer_id", {}, None, _NULL_CUSTOMER_ROW),
+ (
+ "accepted_values",
+ CheckType.ACCEPTED_VALUES,
+ "status",
+ {"values": ["paid", "refunded"]},
+ None,
+ _UNMATCHED_CUSTOMER_ROW,
+ ),
+ ("relationships", CheckType.RELATIONSHIPS, "customer_id", None, "customers", _UNMATCHED_CUSTOMER_ROW),
+ ]
+ )
+ def test_the_stored_query_returns_the_offending_row(
+ self, _name, check_type, column_name, config, related_view, expected_row
+ ) -> None:
+ # Failing rows are never persisted, so a human investigating re-runs this query by hand. It
+ # has to come back with the data that broke, not a column of 1s.
+ merged_config = config if config is not None else self._relationships_config()
+ compiled = self._compile("orders", check_type, column_name, merged_config, related_view)
+
+ response = self._execute(compiled.printed_failing_rows_query)
+
+ assert [dict(zip(response.columns, row)) for row in response.results] == [expected_row]
diff --git a/products/data_quality/backend/tests/test_models.py b/products/data_quality/backend/tests/test_models.py
new file mode 100644
index 000000000000..ce7930ae1227
--- /dev/null
+++ b/products/data_quality/backend/tests/test_models.py
@@ -0,0 +1,121 @@
+from uuid import UUID, uuid4
+
+from posthog.test.base import BaseTest
+
+from django.db import IntegrityError, transaction
+
+from parameterized import parameterized
+
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.data_quality.backend.facade.enums import (
+ CheckRunStatus,
+ CheckType,
+ SubjectStatus,
+ SubjectType,
+ SuiteRunTrigger,
+)
+from products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable
+
+
+class TestDataQualityModels(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.saved_query_id = uuid4()
+
+ def _create_check(self, **kwargs) -> DataQualityCheck:
+ defaults = {
+ "team": self.team,
+ "subject_type": SubjectType.VIEW,
+ "saved_query_id": self.saved_query_id,
+ "subject_name": "orders",
+ "check_type": CheckType.NOT_NULL,
+ "column_name": "customer_id",
+ "fingerprint": "a" * 64,
+ }
+ return DataQualityCheck.objects.for_team(self.team.id).create(**{**defaults, **kwargs})
+
+ def test_same_fingerprint_is_rejected_only_within_a_subject(self) -> None:
+ self._create_check()
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ self._create_check()
+ other_subject = self._create_check(saved_query_id=uuid4(), subject_name="refunds")
+ assert other_subject.pk is not None
+ table_subject = self._create_check(
+ saved_query_id=None, table_id=uuid4(), subject_type=SubjectType.TABLE, subject_name="stripe_charges"
+ )
+ assert table_subject.pk is not None
+
+ def test_orphaned_checks_escape_fingerprint_uniqueness(self) -> None:
+ # SET_NULL orphaning must never be blocked by the constraint, even for twin fingerprints.
+ self._create_check(saved_query_id=None)
+ second = self._create_check(saved_query_id=None)
+ assert second.pk is not None
+
+ def test_subject_binding_rejects_contradictory_rows(self) -> None:
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ self._create_check(table_id=uuid4())
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ self._create_check(subject_type=SubjectType.TABLE)
+
+ def test_blank_names_coexist_but_set_names_are_unique(self) -> None:
+ self._create_check()
+ self._create_check(saved_query_id=uuid4(), subject_name="refunds")
+
+ self._create_check(saved_query_id=uuid4(), subject_name="shipments", name="orders_customer_id_not_null")
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ self._create_check(saved_query_id=uuid4(), subject_name="returns", name="orders_customer_id_not_null")
+
+ @parameterized.expand(
+ [
+ (SubjectType.VIEW, "saved_query_id"),
+ (SubjectType.TABLE, "table_id"),
+ ]
+ )
+ def test_deleting_the_subject_orphans_the_check(self, subject_type, fk_name) -> None:
+ subject_id = self._create_subject(subject_type)
+ check = self._create_check(**{"subject_type": subject_type, "saved_query_id": None, fk_name: subject_id})
+
+ self._delete_subject(subject_type, subject_id)
+
+ check.refresh_from_db()
+ assert getattr(check, fk_name) is None
+ assert check.subject_status == SubjectStatus.ORPHANED
+
+ def _create_subject(self, subject_type: SubjectType) -> UUID:
+ if subject_type is SubjectType.VIEW:
+ return DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="orders", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}
+ ).id
+ return DataWarehouseTable.objects.create(
+ team=self.team, name="stripe_charges", format=DataWarehouseTable.TableFormat.Parquet, url_pattern=""
+ ).id
+
+ def _delete_subject(self, subject_type: SubjectType, subject_id: UUID) -> None:
+ model = DataWarehouseSavedQuery if subject_type is SubjectType.VIEW else DataWarehouseTable
+ model.objects.filter(id=subject_id).delete()
+
+ def test_run_history_survives_deleting_the_definition(self) -> None:
+ check = self._create_check()
+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(
+ team=self.team, trigger=SuiteRunTrigger.MANUAL
+ )
+ run = DataQualityCheckRun.objects.for_team(self.team.id).create(
+ team=self.team,
+ quality_check=check,
+ suite_run=suite_run,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=self.saved_query_id,
+ subject_name="orders",
+ check_type=CheckType.NOT_NULL,
+ check_fingerprint=check.fingerprint,
+ status=CheckRunStatus.FAILED,
+ failed_row_count=3,
+ )
+
+ check.delete()
+
+ run.refresh_from_db()
+ assert run.quality_check_id is None
+ assert run.check_fingerprint == "a" * 64
+ assert run.failed_row_count == 3
diff --git a/products/data_quality/backend/tests/test_subjects.py b/products/data_quality/backend/tests/test_subjects.py
new file mode 100644
index 000000000000..b31451a6ee1f
--- /dev/null
+++ b/products/data_quality/backend/tests/test_subjects.py
@@ -0,0 +1,56 @@
+from uuid import uuid4
+
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from posthog.models.team import Team
+
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.data_quality.backend.facade.enums import SubjectType
+from products.data_quality.backend.logic.subjects import resolve_subject
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable
+
+
+class TestSubjectResolver(BaseTest):
+ def _table(self, name: str = "stripe_customers") -> DataWarehouseTable:
+ return DataWarehouseTable.objects.create(
+ team=self.team, name=name, format="Parquet", url_pattern="s3://bucket/x"
+ )
+
+ def _view(self, name: str = "revenue_view") -> DataWarehouseSavedQuery:
+ return DataWarehouseSavedQuery.objects.create(team=self.team, name=name, query={"kind": "HogQLQuery"})
+
+ def test_resolves_a_table_to_its_queryable_name(self) -> None:
+ table = self._table()
+ resolved = resolve_subject(self.team.id, SubjectType.TABLE, table.id)
+ assert resolved.exists
+ assert resolved.queryable_name == "stripe_customers"
+
+ def test_resolves_a_view_to_its_own_name_even_when_materialized(self) -> None:
+ view = self._view()
+ view.table = self._table("materialized_backing_table")
+ view.save()
+
+ resolved = resolve_subject(self.team.id, SubjectType.VIEW, view.id)
+ assert resolved.queryable_name == "revenue_view"
+
+ @parameterized.expand([(SubjectType.TABLE,), (SubjectType.VIEW,)])
+ def test_unknown_subject_does_not_resolve(self, subject_type: SubjectType) -> None:
+ assert not resolve_subject(self.team.id, subject_type, uuid4()).exists
+
+ def test_soft_deleted_subjects_do_not_resolve(self) -> None:
+ table = self._table()
+ table.deleted = True
+ table.save()
+ view = self._view()
+ view.soft_delete()
+
+ assert not resolve_subject(self.team.id, SubjectType.TABLE, table.id).exists
+ assert not resolve_subject(self.team.id, SubjectType.VIEW, view.id).exists
+
+ def test_another_teams_subject_does_not_resolve(self) -> None:
+ table = self._table()
+ other_team = Team.objects.create(organization=self.organization, name="Other team")
+
+ assert not resolve_subject(other_team.id, SubjectType.TABLE, table.id).exists
diff --git a/products/data_quality/manifest.tsx b/products/data_quality/manifest.tsx
new file mode 100644
index 000000000000..1286662a4eee
--- /dev/null
+++ b/products/data_quality/manifest.tsx
@@ -0,0 +1,13 @@
+import { ProductManifest } from '../../frontend/src/types'
+
+export const manifest: ProductManifest = {
+ name: 'DataQuality',
+ scenes: {},
+ routes: {},
+ redirects: {},
+ urls: {},
+ fileSystemTypes: {},
+ treeItemsNew: [],
+ treeItemsProducts: [],
+ treeItemsMetadata: [],
+}
diff --git a/products/data_quality/package.json b/products/data_quality/package.json
new file mode 100644
index 000000000000..f1bae28c9ced
--- /dev/null
+++ b/products/data_quality/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@posthog/products-data-quality",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"
+ }
+}
diff --git a/products/data_quality/product.yaml b/products/data_quality/product.yaml
new file mode 100644
index 000000000000..222b982c969a
--- /dev/null
+++ b/products/data_quality/product.yaml
@@ -0,0 +1,3 @@
+name: Data quality
+owners:
+ - team-data-modeling
diff --git a/products/data_quality/tsconfig.json b/products/data_quality/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/data_quality/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 10d1e9682c79..d480913745b3 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -1156,6 +1156,7 @@ export type ActivityLogListParams = {
* * `StreamlitApp` - StreamlitApp
* * `Metric` - Metric
* * `TableCertification` - TableCertification
+ * * `DataQualityCheck` - DataQualityCheck
* * `Billing` - Billing
* * `Loop` - Loop
* @minLength 1
@@ -1249,6 +1250,7 @@ export const ActivityLogListScope = {
StreamlitApp: 'StreamlitApp',
Metric: 'Metric',
TableCertification: 'TableCertification',
+ DataQualityCheck: 'DataQualityCheck',
Billing: 'Billing',
Loop: 'Loop',
} as const
@@ -1329,6 +1331,7 @@ export const ActivityLogListScope = {
* * `StreamlitApp` - StreamlitApp
* * `Metric` - Metric
* * `TableCertification` - TableCertification
+ * * `DataQualityCheck` - DataQualityCheck
* * `Billing` - Billing
* * `Loop` - Loop
*/
@@ -1410,6 +1413,7 @@ export const ActivityLogListScopesItem = {
StreamlitApp: 'StreamlitApp',
Metric: 'Metric',
TableCertification: 'TableCertification',
+ DataQualityCheck: 'DataQualityCheck',
Billing: 'Billing',
Loop: 'Loop',
} as const
diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.py
index e226cf413dde..396dc14afb5a 100644
--- a/products/warehouse_sources/backend/facade/api.py
+++ b/products/warehouse_sources/backend/facade/api.py
@@ -55,6 +55,7 @@ __all__ = [
"get_schema",
"list_schemas_for_source",
"get_table",
+ "get_queryable_table",
"list_tables_for_source",
"list_jobs_for_source",
# framework-free helper transforms
@@ -207,6 +208,18 @@ def get_table(table_id: UUID, team_id: int) -> contracts.DataWarehouseTable:
return _to_table(_DataWarehouseTable.objects.get(id=table_id, team_id=team_id))
+def get_queryable_table(table_id: UUID, team_id: int) -> contracts.DataWarehouseTable | None:
+ """The table only if it is still queryable, else None.
+
+ Unlike ``get_table``, this applies the soft-delete and orphaned-source filters and returns
+ None instead of raising, so a caller holding a stored table reference can tell "gone" from
+ "something went wrong".
+ """
+ # raw_objects skips the eager schema prefetch/joins objects does -- the mapper only reads scalars.
+ table = _DataWarehouseTable.raw_objects.queryable().filter(id=table_id, team_id=team_id).first()
+ return _to_table(table) if table is not None else None
+
+
def list_tables_for_source(source_id: UUID, team_id: int) -> list[contracts.DataWarehouseTable]:
qs = _DataWarehouseTable.objects.filter(team_id=team_id, external_data_source_id=source_id).exclude(deleted=True)
return [_to_table(t) for t in qs]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 93db00050ea6..267b2d6379a2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -79548,6 +79548,7 @@ export namespace Schemas {
* * `StreamlitApp` - StreamlitApp
* * `Metric` - Metric
* * `TableCertification` - TableCertification
+ * * `DataQualityCheck` - DataQualityCheck
* * `Billing` - Billing
* * `Loop` - Loop
* @minLength 1
@@ -79642,6 +79643,7 @@ export namespace Schemas {
StreamlitApp: 'StreamlitApp',
Metric: 'Metric',
TableCertification: 'TableCertification',
+ DataQualityCheck: 'DataQualityCheck',
Billing: 'Billing',
Loop: 'Loop',
} as const;
@@ -79722,6 +79724,7 @@ export namespace Schemas {
* * `StreamlitApp` - StreamlitApp
* * `Metric` - Metric
* * `TableCertification` - TableCertification
+ * * `DataQualityCheck` - DataQualityCheck
* * `Billing` - Billing
* * `Loop` - Loop
*/
@@ -79804,6 +79807,7 @@ export namespace Schemas {
StreamlitApp: 'StreamlitApp',
Metric: 'Metric',
TableCertification: 'TableCertification',
+ DataQualityCheck: 'DataQualityCheck',
Billing: 'Billing',
Loop: 'Loop',
} as const;
diff --git a/tach.toml b/tach.toml
index 15fabf26b4cc..bf5e1c5bbcc0 100644
--- a/tach.toml
+++ b/tach.toml
@@ -90,6 +90,7 @@ depends_on = [
"products.dashboards",
"products.data_catalog",
"products.data_modeling",
+ "products.data_quality",
"products.data_warehouse",
"products.demo",
"products.early_access_features",
@@ -1243,6 +1244,15 @@ path = "products.apm"
depends_on = ["posthog"]
layer = "modules"
+[[modules]]
+path = "products.data_quality"
+depends_on = [
+ "posthog",
+ "products.data_modeling",
+ "products.warehouse_sources",
+]
+layer = "modules"
+
[[interfaces]]
expose = [
"backend\\.facade.*",
@@ -1251,3 +1261,12 @@ expose = [
from = [
"products.apm",
]
+
+[[interfaces]]
+expose = [
+ "backend\\.facade.*",
+ "backend\\.presentation\\.views.*",
+]
+from = [
+ "products.data_quality",
+]