:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-quality): run check suites on Temporal when a subject's data changes (#74692)
Thiago Salvatore4c5132faca2c
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex 54c9063ecb50..c8c03a9befe8 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -830,6 +830,8 @@ jobs:- 'posthog/temporal/data_warehouse/**'- 'posthog/temporal/common/**'- 'posthog/warehouse/**'+ - 'products/data_catalog/**'+ - 'products/data_quality/**'- 'products/data_modeling/**'- 'products/data_warehouse/**'- 'posthog/management/commands/**'diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 163eb2b4649a..b67ad4d3c6c9 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -53,6 +53,7 @@ class Product(StrEnum):CONVERSATIONS = "conversations"CUSTOMER_ANALYTICS = "customer_analytics"DATA_CATALOG = "data_catalog"+ DATA_QUALITY = "data_quality"ENDPOINTS = "endpoints"ENGINEERING_ANALYTICS = "engineering_analytics"ERROR_TRACKING = "error_tracking"@@ -112,6 +113,7 @@ class Feature(StrEnum):INGESTION_WARNINGS = "ingestion_warnings"PREAGGREGATION = "preaggregation"DATA_DELETION = "data_deletion"+ DATA_QUALITY_CHECK = "data_quality_check" # one data quality check assertion against its subjectENRICHMENT = "enrichment" # background tasks that derive/sync data (not customer-facing)EVENT_FILTERS = "event_filters"SCHEMA_INTROSPECTION = "schema_introspection"@@ -485,6 +487,12 @@ class QueryTags(BaseModel):filter_by_type: Optional[list[str]] = Nonebreakdown_by: Optional[list[str]] = None+ # data quality+ data_quality_check_id: Optional[str] = None+ data_quality_check_type: Optional[str] = None # not_null, unique, freshness, custom_sql, ...+ data_quality_subject_type: Optional[str] = None # table or view+ data_quality_subject_id: Optional[str] = None+# data warehousetrend_volume_display: Optional[str] = Nonetable_id: Optional[uuid.UUID] = Nonediff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 7dc3506807c2..51ffce36c258 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -180,6 +180,10 @@ from products.customer_analytics.backend.facade.temporal import (ACTIVITIES as CUSTOMER_ANALYTICS_ACTIVITIES,WORKFLOWS as CUSTOMER_ANALYTICS_WORKFLOWS,)+from products.data_quality.backend.facade.temporal import (+ ACTIVITIES as DATA_QUALITY_ACTIVITIES,+ WORKFLOWS as DATA_QUALITY_WORKFLOWS,+)from products.engineering_analytics.backend.facade.temporal import (CI_SIGNALS_ACTIVITIES,CI_SIGNALS_WORKFLOWS,@@ -305,8 +309,8 @@ _task_queue_specs = [),(settings.DATA_MODELING_TASK_QUEUE,- DATA_MODELING_WORKFLOWS,- DATA_MODELING_ACTIVITIES,+ DATA_MODELING_WORKFLOWS + DATA_QUALITY_WORKFLOWS,+ DATA_MODELING_ACTIVITIES + DATA_QUALITY_ACTIVITIES,),(settings.GENERAL_PURPOSE_TASK_QUEUE,diff --git a/posthog/temporal/data_modeling/workflows/execute_dag.py b/posthog/temporal/data_modeling/workflows/execute_dag.pyindex b8832b8b9a7c..566717daa6fb 100644--- a/posthog/temporal/data_modeling/workflows/execute_dag.py+++ b/posthog/temporal/data_modeling/workflows/execute_dag.py@@ -34,6 +34,8 @@ from posthog.temporal.data_modeling.workflows.materialize_view import ()from products.data_modeling.backend.facade.models import DataModelingJobEngine+from products.data_quality.backend.facade.contracts import CHECK_SUITE_WORKFLOW_NAME, MATERIALIZATION_GATE_ACTIVITY_NAME+from products.data_quality.backend.facade.enums import SuiteRunTriggerMAX_CONCURRENT_CHILDREN = 10@@ -411,8 +413,6 @@ class ExecuteDAGWorkflow(PostHogWorkflow):if not nr.success:failed_node_set.add(nr.node_id)- # Safe to add without a workflow patch: this is the last command before the workflow- # returns, so a replayed history either stops short of it or has already completed.if skipped_jobs:await temporalio.workflow.execute_activity(record_skipped_data_modeling_jobs_activity,@@ -460,6 +460,8 @@ class ExecuteDAGWorkflow(PostHogWorkflow):get_dag_node_count_metric("failed").record(failed_nodes)get_dag_node_count_metric("skipped").record(skipped_nodes)+ await self._run_data_quality_checks(inputs, node_results)+return ExecuteDAGResult(dag_id=inputs.dag_id,scheduled_nodes=len(node_results),@@ -469,3 +471,45 @@ class ExecuteDAGWorkflow(PostHogWorkflow):duration_seconds=duration_seconds,node_results=node_results,)++ async def _run_data_quality_checks(self, inputs: ExecuteDAGInputs, node_results: list[NodeResult]) -> None:+ """Fire the check suite for the models this run brought up to date.++ Best-effort and fully isolated: started by registered name so data_modeling never imports+ the catalog product, and ABANDON so a check suite can neither delay nor fail the DAG. The+ node ids come from recorded activity results, so replay stays deterministic.++ The gate activity owns the feature flag and the "are there any checks here" question, both+ of which need the database. Asking first keeps a team with no checks, or an org that never+ opted in, from paying for a child workflow and a suite row on every materialization.+ """+ checkable_node_ids = [result.node_id for result in node_results if result.success and not result.skipped]+ if not checkable_node_ids:+ return++ try:+ checks_needed = await temporalio.workflow.execute_activity(+ MATERIALIZATION_GATE_ACTIVITY_NAME,+ {"team_id": inputs.team_id, "node_ids": checkable_node_ids},+ start_to_close_timeout=dt.timedelta(minutes=1),+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),+ )+ if not checks_needed:+ return++ await temporalio.workflow.start_child_workflow(+ CHECK_SUITE_WORKFLOW_NAME,+ {+ "team_id": inputs.team_id,+ "trigger": SuiteRunTrigger.MATERIALIZATION.value,+ "node_ids": checkable_node_ids,+ },+ id=f"data-quality-run-suite-{inputs.dag_id}-{temporalio.workflow.info().run_id}",+ parent_close_policy=ParentClosePolicy.ABANDON,+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1),+ )+ except Exception as e:+ capture_exception(e)+ temporalio.workflow.logger.warning(+ "Could not start the data quality check suite", extra=inputs.properties_to_log+ )diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex cffd0e7d3dab..4d45ed0abd06 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -84,6 +84,7 @@ from products.business_knowledge.backend.temporal.schedule import create_businesfrom products.conversations.backend.temporal.channel_summary.schedule import create_channel_summary_coordinator_schedulefrom products.conversations.backend.temporal.schedule import create_support_reply_coordinator_schedulefrom products.customer_analytics.backend.facade.temporal import create_calendar_sync_coordinator_schedule+from products.data_quality.backend.facade.temporal import create_cleanup_data_quality_check_runs_schedulefrom products.engineering_analytics.backend.facade.temporal import (create_ci_signals_coordinator_schedule,create_github_job_logs_coordinator_schedule,@@ -882,6 +883,7 @@ schedules = [create_github_job_logs_coordinator_schedule,create_review_hog_finding_outcomes_schedule,create_ci_signals_coordinator_schedule,+ create_cleanup_data_quality_check_runs_schedule,]if settings.CLOUD_DEPLOYMENT:diff --git a/posthog/temporal/tests/data_modeling/test_execute_dag_data_quality.py b/posthog/temporal/tests/data_modeling/test_execute_dag_data_quality.pynew file mode 100644index 000000000000..76919f0fc042--- /dev/null+++ b/posthog/temporal/tests/data_modeling/test_execute_dag_data_quality.py@@ -0,0 +1,121 @@+import uuid+import datetime as dt++import pytest++import temporalio.worker+from temporalio import (+ activity as temporal_activity,+ workflow as temporal_workflow,+)+from temporalio.testing import WorkflowEnvironment++from posthog.temporal.data_modeling.activities import GetDAGStructureInputs+from posthog.temporal.data_modeling.activities.get_dag_structure import DAG as DAGPlan+from posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputs, ExecuteDAGResult, ExecuteDAGWorkflow+from posthog.temporal.tests.data_modeling.test_execute_dag_workflow import (+ MockMaterializeViewWorkflow,+ _mock_workflow_should_fail,+ stub_preempt_dag_run,+)++from products.data_quality.backend.facade.contracts import MATERIALIZATION_GATE_ACTIVITY_NAME++pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]++_suite_runs_started: list[dict] = []+++@temporal_workflow.defn(name="data-quality-run-suite")+class MockCheckSuiteWorkflow:+ @temporal_workflow.run+ async def run(self, inputs: dict) -> dict:+ _suite_runs_started.append(inputs)+ return {"suite_run_id": "s-1", "status": "empty"}+++class TestPostMaterializationChecks:+ @pytest.fixture(autouse=True)+ def reset_mock_state(self):+ _suite_runs_started.clear()+ _mock_workflow_should_fail.clear()+ yield+ _suite_runs_started.clear()+ _mock_workflow_should_fail.clear()++ async def _run_dag(+ self,+ team_id: int,+ node_ids: list[str],+ *,+ ephemeral_node_ids: list[str] | None = None,+ register_suite: bool = True,+ checks_needed: bool = True,+ ) -> ExecuteDAGResult:+ executable = node_ids + (ephemeral_node_ids or [])++ @temporal_activity.defn(name="get_dag_structure_activity")+ async def stub_get_dag_structure(_: GetDAGStructureInputs) -> DAGPlan:+ return DAGPlan(+ nodes=executable,+ executable_nodes=executable,+ edges=[],+ ephemeral_nodes=ephemeral_node_ids or [],+ )++ @temporal_activity.defn(name=MATERIALIZATION_GATE_ACTIVITY_NAME)+ async def stub_materialization_gate(_: dict) -> bool:+ return checks_needed++ workflows = [ExecuteDAGWorkflow, MockMaterializeViewWorkflow]+ if register_suite:+ workflows.append(MockCheckSuiteWorkflow)++ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with temporalio.worker.Worker(+ env.client,+ task_queue="test-queue",+ workflows=workflows,+ activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_materialization_gate],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ return await env.client.execute_workflow(+ ExecuteDAGWorkflow.run,+ ExecuteDAGInputs(team_id=team_id, dag_id="dag-1"),+ id=f"test-data-quality-{uuid.uuid4()}",+ task_queue="test-queue",+ execution_timeout=dt.timedelta(seconds=30),+ )++ async def test_every_node_the_run_brought_up_to_date_is_handed_to_the_check_suite(self, ateam) -> None:+ materialized, failing, ephemeral = str(uuid.uuid4()), str(uuid.uuid4()), str(uuid.uuid4())+ _mock_workflow_should_fail.add(failing)++ result = await self._run_dag(ateam.pk, [materialized, failing], ephemeral_node_ids=[ephemeral])++ assert result.successful_nodes == 2+ assert len(_suite_runs_started) == 1+ assert sorted(_suite_runs_started[0]["node_ids"]) == sorted([materialized, ephemeral])+ assert _suite_runs_started[0]["trigger"] == "materialization"+ assert _suite_runs_started[0]["team_id"] == ateam.pk++ async def test_no_suite_starts_when_nothing_materialized(self, ateam) -> None:+ failing = str(uuid.uuid4())+ _mock_workflow_should_fail.add(failing)++ result = await self._run_dag(ateam.pk, [failing])++ assert result.successful_nodes == 0+ assert _suite_runs_started == []++ async def test_no_suite_starts_when_the_gate_says_the_team_has_no_checks_to_run(self, ateam) -> None:+ result = await self._run_dag(ateam.pk, [str(uuid.uuid4())], checks_needed=False)++ assert result.successful_nodes == 1+ assert _suite_runs_started == []++ async def test_a_check_suite_that_cannot_start_does_not_fail_the_dag(self, ateam) -> None:+ result = await self._run_dag(ateam.pk, [str(uuid.uuid4())], register_suite=False)++ assert result.successful_nodes == 1+ assert result.failed_nodes == 0diff --git a/products/data_quality/backend/apps.py b/products/data_quality/backend/apps.pyindex 6de935e7719a..717f21c1ce00 100644--- a/products/data_quality/backend/apps.py+++ b/products/data_quality/backend/apps.py@@ -9,4 +9,9 @@ class DataQualityConfig(AppConfig):verbose_name = "Data quality"def ready(self) -> None:+ from products.warehouse_sources.backend.facade.hooks import register_data_quality_checks_gate # noqa: PLC0415+from . import activity_logging # noqa: F401, PLC0415+ from .logic.triggers import source_sync_checks_needed # noqa: PLC0415++ register_data_quality_checks_gate(source_sync_checks_needed)diff --git a/products/data_quality/backend/facade/contracts.py b/products/data_quality/backend/facade/contracts.pyindex 95ca332d433d..affbe8871be8 100644--- a/products/data_quality/backend/facade/contracts.py+++ b/products/data_quality/backend/facade/contracts.py@@ -7,6 +7,10 @@ Frozen, framework-free values other products need. No Django imports.from dataclasses import dataclass, fieldfrom typing import Any+CHECK_SUITE_WORKFLOW_NAME = "data-quality-run-suite"++MATERIALIZATION_GATE_ACTIVITY_NAME = "data-quality-materialization-gate"+@dataclass(frozen=True)class CheckTypeInfo:diff --git a/products/data_quality/backend/facade/flags.py b/products/data_quality/backend/facade/flags.pynew file mode 100644index 000000000000..5e207d129239--- /dev/null+++ b/products/data_quality/backend/facade/flags.py@@ -0,0 +1,17 @@+"""Feature-flag re-export.++Lets core code (the HogQL database builder) check the product flag without pulling the facade's+heavier logic surface onto its import path.+"""++from ..logic.flags import (+ DATA_QUALITY_CHECKS_FEATURE_FLAG,+ is_data_quality_checks_enabled,+ is_data_quality_checks_enabled_for_team_id,+)++__all__ = [+ "DATA_QUALITY_CHECKS_FEATURE_FLAG",+ "is_data_quality_checks_enabled",+ "is_data_quality_checks_enabled_for_team_id",+]diff --git a/products/data_quality/backend/facade/temporal.py b/products/data_quality/backend/facade/temporal.pynew file mode 100644index 000000000000..5faea27ef280--- /dev/null+++ b/products/data_quality/backend/facade/temporal.py@@ -0,0 +1,15 @@+"""Facade re-exports for Temporal wiring.++The worker bootstrap (`start_temporal_worker`) registers catalog workflows and activities through+these re-exports rather than importing ``backend.temporal`` directly.+"""++from ..temporal import (+ ACTIVITIES as ACTIVITIES,+ WORKFLOWS as WORKFLOWS,+)+from ..temporal.contracts import RunCheckSuiteInputs as RunCheckSuiteInputs+from ..temporal.schedule import (+ create_cleanup_data_quality_check_runs_schedule as create_cleanup_data_quality_check_runs_schedule,+)+from .contracts import CHECK_SUITE_WORKFLOW_NAME as CHECK_SUITE_WORKFLOW_NAMEdiff --git a/products/data_quality/backend/logic/flags.py b/products/data_quality/backend/logic/flags.pynew file mode 100644index 000000000000..d37defec0666--- /dev/null+++ b/products/data_quality/backend/logic/flags.py@@ -0,0 +1,34 @@+from typing import TYPE_CHECKING++from django.conf import settings++from posthog.ph_client import feature_enabled_or_false++if TYPE_CHECKING:+ from posthog.models.team import Team++DATA_QUALITY_CHECKS_FEATURE_FLAG = "data-quality-checks"+++def is_data_quality_checks_enabled(team: "Team") -> bool:+ """The `data-quality-checks` flag check, org-keyed. Canonical home for the check -- gate any+ data-quality surface (API, information_schema tables, MCP tools, triggers) through here."""+ if settings.DEBUG:+ return True+ return feature_enabled_or_false(+ DATA_QUALITY_CHECKS_FEATURE_FLAG,+ str(team.organization_id),+ groups={"organization": str(team.organization_id)},+ group_properties={"organization": {"id": str(team.organization_id)}},+ send_feature_flag_events=False,+ )+++def is_data_quality_checks_enabled_for_team_id(team_id: int) -> bool:+ """Flag check for callers that only hold a team id (trigger gates, activities)."""+ from posthog.models.team import Team # noqa: PLC0415 — the app registry is not ready at import time++ team = Team.objects.filter(id=team_id).only("id", "organization_id").first()+ if team is None:+ return False+ return is_data_quality_checks_enabled(team)diff --git a/products/data_quality/backend/logic/runner.py b/products/data_quality/backend/logic/runner.pynew file mode 100644index 000000000000..2081b8031b15--- /dev/null+++ b/products/data_quality/backend/logic/runner.py@@ -0,0 +1,183 @@+"""Execute one check and record the result.++Never called in-request: every path into here comes from a Temporal activity, because a check runs+an arbitrary warehouse query and there is no response worth waiting for.++A check that cannot be compiled or executed is recorded as ``errored``, not raised. One broken+check must not take down the rest of its suite.+"""++import time+from dataclasses import dataclass, replace+from datetime import UTC, datetime+from typing import Any++from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.models.scoping import team_scope+from posthog.models.team import Team++from ..facade.enums import CheckRunStatus, CheckSeverity, SubjectStatus+from ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from .compiler import compile_check, related_subject_ref+from .contracts import CompiledCheck, Evaluation+from .subjects import resolve_subject++QUERY_TYPE = "data_quality_check"+++@dataclass(frozen=True)+class CheckOutcome:+ """What one check execution produced, before it is written down."""++ status: CheckRunStatus+ failed_row_count: int | None = None+ observed_value: float | None = None+ compiled_query: str = ""+ error: str = ""+ became_failing: bool = False+++def run_check(check: DataQualityCheck, suite_run: DataQualitySuiteRun, team: Team) -> CheckOutcome:+ """Compile, execute, and persist one check. Updates the check's denormalized status.++ Runs under an explicit team scope because there is no request context out here, and saving a+ check reads its own previous state through the fail-closed manager to build the activity log.+ """+ started_at = datetime.now(UTC)+ monotonic_start = time.monotonic()+ previous_status = check.last_status++ try:+ outcome = _execute(check, team)+ except Exception as err:+ outcome = CheckOutcome(status=CheckRunStatus.ERRORED, error=str(err))++ duration_ms = int((time.monotonic() - monotonic_start) * 1000)+ with team_scope(team.id):+ _record_run(check, suite_run, outcome, started_at, duration_ms)+ _update_check(check, outcome)++ became_failing = (+ outcome.status is CheckRunStatus.FAILED+ and previous_status != CheckRunStatus.FAILED+ and check.severity == CheckSeverity.ERROR+ )+ return replace(outcome, became_failing=became_failing)+++def _execute(check: DataQualityCheck, team: Team) -> CheckOutcome:+ if check.subject_uuid is None:+ check.subject_status = SubjectStatus.ORPHANED+ return CheckOutcome(status=CheckRunStatus.SKIPPED, error="The subject was deleted.")++ subject = resolve_subject(team.id, check.subject_type, check.subject_uuid)+ if not subject.exists:+ check.subject_status = SubjectStatus.ORPHANED+ return CheckOutcome(status=CheckRunStatus.SKIPPED, error="The subject no longer resolves.")++ check.subject_status = SubjectStatus.ACTIVE+ check.subject_name = subject.name++ related = related_subject_ref(check.check_type, check.config)+ compiled = compile_check(+ check_type=check.check_type,+ subject=subject,+ column_name=check.column_name,+ config=check.config,+ related_subject=resolve_subject(team.id, *related) if related else None,+ )+ with tags_context(+ product=Product.DATA_QUALITY,+ feature=Feature.DATA_QUALITY_CHECK,+ data_quality_check_id=str(check.id),+ data_quality_check_type=check.check_type,+ data_quality_subject_type=subject.subject_type,+ data_quality_subject_id=subject.subject_uuid,+ ):+ response = execute_hogql_query(query=compiled.query, team=team, query_type=QUERY_TYPE)+ return _interpret(compiled, check.config, response.results, response.columns or [])+++def _interpret(+ compiled: CompiledCheck,+ config: dict[str, Any],+ results: list[Any] | None,+ columns: list[str],+) -> CheckOutcome:+ if not results:+ return CheckOutcome(+ status=CheckRunStatus.ERRORED,+ compiled_query=compiled.printed_failing_rows_query,+ error="The check query returned no rows.",+ )++ row = dict(zip(columns, results[0]))+ observed = _as_float(row.get("observed_value"))++ if compiled.evaluation is Evaluation.BOUNDS:+ status = CheckRunStatus.PASSED if _within_bounds(observed, config) else CheckRunStatus.FAILED+ failed_row_count = None+ else:+ failed_row_count = int(row.get("failure_count") or 0)+ status = CheckRunStatus.PASSED if failed_row_count == 0 else CheckRunStatus.FAILED++ return CheckOutcome(+ status=status,+ failed_row_count=failed_row_count,+ observed_value=observed,+ compiled_query=compiled.printed_failing_rows_query,+ )+++def _within_bounds(observed: float | None, config: dict[str, Any]) -> bool:+ if observed is None:+ return False+ minimum, maximum = config.get("min"), config.get("max")+ if minimum is not None and observed < minimum:+ return False+ return not (maximum is not None and observed > maximum)+++def _as_float(value: Any) -> float | None:+ try:+ return float(value) if value is not None else None+ except (TypeError, ValueError):+ return None+++def _record_run(+ check: DataQualityCheck,+ suite_run: DataQualitySuiteRun,+ outcome: CheckOutcome,+ started_at: datetime,+ duration_ms: int,+) -> None:+ if check.subject_uuid is None:+ return+ DataQualityCheckRun.objects.for_team(check.team_id).create(+ team_id=check.team_id,+ quality_check=check,+ suite_run=suite_run,+ subject_type=check.subject_type,+ subject_uuid=check.subject_uuid,+ subject_name=check.subject_name,+ check_type=check.check_type,+ check_fingerprint=check.fingerprint,+ column_name=check.column_name,+ status=outcome.status,+ failed_row_count=outcome.failed_row_count,+ observed_value=outcome.observed_value,+ compiled_query=outcome.compiled_query,+ error=outcome.error,+ duration_ms=duration_ms,+ started_at=started_at,+ finished_at=datetime.now(UTC),+ )+++def _update_check(check: DataQualityCheck, outcome: CheckOutcome) -> None:+ check.last_status = outcome.status+ check.last_run_at = datetime.now(UTC)+ check.save(update_fields=["last_status", "last_run_at", "subject_name", "subject_status", "updated_at"])diff --git a/products/data_quality/backend/logic/triggers.py b/products/data_quality/backend/logic/triggers.pynew file mode 100644index 000000000000..fca6244734a3--- /dev/null+++ b/products/data_quality/backend/logic/triggers.py@@ -0,0 +1,37 @@+"""Gates the event-driven triggers consult before starting a check suite.++Called from other products' pipelines (via inversion hooks), so they must be cheap, never raise,+and answer false when the product flag is off.+"""++import uuid+from collections.abc import Iterable++from products.data_modeling.backend.facade import api as data_modeling_facade++from .flags import is_data_quality_checks_enabled_for_team_id+++def source_sync_checks_needed(team_id: int, table_id: "str | uuid.UUID") -> bool:+ """Whether a completed sync of this table should start a check suite."""+ from ..models import DataQualityCheck # noqa: PLC0415 — the app registry is not ready at import time++ if not is_data_quality_checks_enabled_for_team_id(team_id):+ return False+ return DataQualityCheck.objects.for_team(team_id).filter(table_id=table_id, enabled=True, deleted=False).exists()+++def materialization_checks_needed(team_id: int, node_ids: Iterable["str | uuid.UUID"]) -> bool:+ """Whether a DAG run that materialized these nodes should start a check suite."""+ from ..models import DataQualityCheck # noqa: PLC0415 — the app registry is not ready at import time++ if not is_data_quality_checks_enabled_for_team_id(team_id):+ return False+ saved_query_ids = data_modeling_facade.get_saved_query_ids_for_nodes(team_id, node_ids)+ if not saved_query_ids:+ return False+ return (+ DataQualityCheck.objects.for_team(team_id)+ .filter(saved_query_id__in=saved_query_ids, enabled=True, deleted=False)+ .exists()+ )diff --git a/products/data_quality/backend/temporal/__init__.py b/products/data_quality/backend/temporal/__init__.pynew file mode 100644index 000000000000..f854c12f7847--- /dev/null+++ b/products/data_quality/backend/temporal/__init__.py@@ -0,0 +1,35 @@+"""Temporal wiring for data_quality. Registered on the data-modeling task queue."""++from collections.abc import Callable+from typing import Any++from posthog.temporal.common.base import PostHogWorkflow++from .activities.cleanup import cleanup_check_runs_activity+from .activities.finalize_check_suite import (+ finalize_check_suite_activity,+ mark_check_suite_empty_activity,+ mark_check_suite_failed_activity,+)+from .activities.materialization_gate import materialization_gate_activity+from .activities.prepare_check_suite import prepare_check_suite_activity+from .activities.run_check_batch import run_check_batch_activity+from .workflows.cleanup import CleanupCheckRunsWorkflow+from .workflows.run_check_suite import RunCheckSuiteWorkflow++WORKFLOWS: list[type[PostHogWorkflow]] = [+ RunCheckSuiteWorkflow,+ CleanupCheckRunsWorkflow,+]++ACTIVITIES: list[Callable[..., Any]] = [+ materialization_gate_activity,+ prepare_check_suite_activity,+ run_check_batch_activity,+ finalize_check_suite_activity,+ mark_check_suite_empty_activity,+ mark_check_suite_failed_activity,+ cleanup_check_runs_activity,+]++__all__ = ["ACTIVITIES", "WORKFLOWS"]diff --git a/products/data_quality/backend/temporal/activities/cleanup.py b/products/data_quality/backend/temporal/activities/cleanup.pynew file mode 100644index 000000000000..2e2386576bc1--- /dev/null+++ b/products/data_quality/backend/temporal/activities/cleanup.py@@ -0,0 +1,72 @@+from datetime import UTC, datetime, timedelta++from django.db.models import Exists, OuterRef, Q++from asgiref.sync import sync_to_async+from temporalio import activity++from posthog.temporal.common.logger import get_logger++from ...facade.enums import SuiteRunStatus+from ...models import DataQualityCheckRun, DataQualitySuiteRun+from ..contracts import CleanupOutcome++LOGGER = get_logger(__name__)++COMPILED_QUERY_RETENTION_DAYS = 30+CHECK_RUN_RETENTION_DAYS = 365+SUITE_RUN_RETENTION_DAYS = 90+STALE_SUITE_HOURS = 24+STALE_SUITE_ERROR = "The workflow stopped without recording a result."+++async def cleanup_check_runs_activity() -> CleanupOutcome:+ return await sync_to_async(_cleanup)()+++def _cleanup() -> CleanupOutcome:+ """Retention sweep across every team, which is why it uses the unscoped manager."""+ now = datetime.now(UTC)+ runs = DataQualityCheckRun.objects.unscoped()++ queries_cleared = (+ runs.filter(created_at__lt=now - timedelta(days=COMPILED_QUERY_RETENTION_DAYS))+ .exclude(compiled_query="")+ .update(compiled_query="")+ )++ has_newer_run = runs.filter(quality_check_id=OuterRef("quality_check_id"), created_at__gt=OuterRef("created_at"))+ runs_deleted, _ = (+ runs.filter(created_at__lt=now - timedelta(days=CHECK_RUN_RETENTION_DAYS))+ .filter(Q(quality_check_id__isnull=True) | Exists(has_newer_run))+ .delete()+ )++ backs_a_run = DataQualityCheckRun.objects.unscoped().filter(suite_run_id=OuterRef("id"))+ suites_deleted, _ = (+ DataQualitySuiteRun.objects.unscoped()+ .filter(created_at__lt=now - timedelta(days=SUITE_RUN_RETENTION_DAYS))+ .filter(~Exists(backs_a_run))+ .delete()+ )++ stale_failed = (+ DataQualitySuiteRun.objects.unscoped()+ .filter(status=SuiteRunStatus.RUNNING, created_at__lt=now - timedelta(hours=STALE_SUITE_HOURS))+ .update(status=SuiteRunStatus.FAILED, error=STALE_SUITE_ERROR, finished_at=now, updated_at=now)+ )++ LOGGER.info(+ "Cleaned up data quality history",+ queries_cleared=queries_cleared,+ runs_deleted=runs_deleted,+ suites_deleted=suites_deleted,+ stale_suites_failed=stale_failed,+ )+ return CleanupOutcome(+ compiled_queries_cleared=queries_cleared,+ check_runs_deleted=runs_deleted,+ suite_runs_deleted=suites_deleted,+ stale_suites_failed=stale_failed,+ )diff --git a/products/data_quality/backend/temporal/activities/finalize_check_suite.py b/products/data_quality/backend/temporal/activities/finalize_check_suite.pynew file mode 100644index 000000000000..a16658c96c78--- /dev/null+++ b/products/data_quality/backend/temporal/activities/finalize_check_suite.py@@ -0,0 +1,94 @@+from datetime import UTC, datetime++from asgiref.sync import sync_to_async+from temporalio import activity++from posthog.temporal.common.logger import get_logger++from ...facade.enums import SuiteRunStatus+from ...models import DataQualitySuiteRun+from ..contracts import CheckSuiteResult, FinalizeCheckSuiteInputs, MarkSuiteFailedInputs++LOGGER = get_logger(__name__)+++async def finalize_check_suite_activity(inputs: FinalizeCheckSuiteInputs) -> CheckSuiteResult:+ return await sync_to_async(_finalize)(inputs)+++def _finalize(inputs: FinalizeCheckSuiteInputs) -> CheckSuiteResult:+ suite_run = DataQualitySuiteRun.objects.for_team(inputs.team_id).get(id=inputs.suite_run_id)++ suite_run.checks_passed = sum(outcome.passed for outcome in inputs.outcomes)+ suite_run.checks_failed = sum(outcome.failed for outcome in inputs.outcomes)+ suite_run.checks_errored = sum(outcome.errored for outcome in inputs.outcomes)+ suite_run.checks_skipped = sum(outcome.skipped for outcome in inputs.outcomes)+ suite_run.status = SuiteRunStatus.COMPLETED+ suite_run.finished_at = datetime.now(UTC)+ suite_run.save(+ update_fields=[+ "checks_passed",+ "checks_failed",+ "checks_errored",+ "checks_skipped",+ "status",+ "finished_at",+ "updated_at",+ ]+ )++ LOGGER.info(+ "Finalized check suite",+ suite_run_id=inputs.suite_run_id,+ passed=suite_run.checks_passed,+ failed=suite_run.checks_failed,+ errored=suite_run.checks_errored,+ )+ return CheckSuiteResult(+ suite_run_id=str(suite_run.id),+ status=SuiteRunStatus.COMPLETED,+ checks_passed=suite_run.checks_passed,+ checks_failed=suite_run.checks_failed,+ checks_errored=suite_run.checks_errored,+ checks_skipped=suite_run.checks_skipped,+ checks_failed_blocking=sum(outcome.failed_blocking for outcome in inputs.outcomes),+ )+++async def mark_check_suite_empty_activity(inputs: FinalizeCheckSuiteInputs) -> CheckSuiteResult:+ return await sync_to_async(_mark_empty)(inputs)+++def _mark_empty(inputs: FinalizeCheckSuiteInputs) -> CheckSuiteResult:+ """An empty suite is a normal outcome, not a failure -- most materializations have no checks."""+ suite_run = DataQualitySuiteRun.objects.for_team(inputs.team_id).get(id=inputs.suite_run_id)+ suite_run.status = SuiteRunStatus.EMPTY+ suite_run.finished_at = datetime.now(UTC)+ suite_run.save(update_fields=["status", "finished_at", "updated_at"])+ return CheckSuiteResult(suite_run_id=str(suite_run.id), status=SuiteRunStatus.EMPTY)+++async def mark_check_suite_failed_activity(inputs: MarkSuiteFailedInputs) -> None:+ await sync_to_async(_mark_failed)(inputs)+++def _mark_failed(inputs: MarkSuiteFailedInputs) -> None:+ """Move a suite off RUNNING when the workflow gives up, so a poller sees a terminal state.++ A conditional update rather than a load-and-save: it must not clobber a suite another attempt+ already finalized, and it stays a no-op when there is nothing to fail.+ """+ updated = (+ DataQualitySuiteRun.objects.for_team(inputs.team_id)+ .filter(id=inputs.suite_run_id, status=SuiteRunStatus.RUNNING)+ .update(+ status=SuiteRunStatus.FAILED,+ error=inputs.error,+ finished_at=datetime.now(UTC),+ updated_at=datetime.now(UTC),+ )+ )+ LOGGER.info("Marked check suite failed", suite_run_id=inputs.suite_run_id, updated=updated)diff --git a/products/data_quality/backend/temporal/activities/materialization_gate.py b/products/data_quality/backend/temporal/activities/materialization_gate.pynew file mode 100644index 000000000000..26f1037bc911--- /dev/null+++ b/products/data_quality/backend/temporal/activities/materialization_gate.py@@ -0,0 +1,17 @@+from asgiref.sync import sync_to_async+from temporalio import activity++from ...facade.contracts import MATERIALIZATION_GATE_ACTIVITY_NAME+from ...logic.triggers import materialization_checks_needed+from ..contracts import MaterializationGateInputs++[email protected](name=MATERIALIZATION_GATE_ACTIVITY_NAME)+async def materialization_gate_activity(inputs: MaterializationGateInputs) -> bool:+ """Whether the DAG workflow should start a suite at all.++ Lives on the activity side because the answer needs the feature flag and the database, which a+ workflow may not touch. Asking before the start keeps a flag-disabled org from paying for a+ child workflow and an empty suite row on every materialization.+ """+ return await sync_to_async(materialization_checks_needed)(inputs.team_id, inputs.node_ids)diff --git a/products/data_quality/backend/temporal/activities/prepare_check_suite.py b/products/data_quality/backend/temporal/activities/prepare_check_suite.pynew file mode 100644index 000000000000..88cad5904549--- /dev/null+++ b/products/data_quality/backend/temporal/activities/prepare_check_suite.py@@ -0,0 +1,98 @@+from datetime import UTC, datetime++from django.db import models++from asgiref.sync import sync_to_async+from temporalio import activity++from posthog.temporal.common.logger import get_logger++from products.data_modeling.backend.facade import api as data_modeling_facade++from ...facade.enums import SubjectType+from ...logic.flags import is_data_quality_checks_enabled_for_team_id+from ...models import DataQualityCheck, DataQualitySuiteRun+from ..contracts import PreparedSuite, RunCheckSuiteInputs++LOGGER = get_logger(__name__)++CHECKS_PER_BATCH = 25+++async def prepare_check_suite_activity(inputs: RunCheckSuiteInputs) -> PreparedSuite:+ return await sync_to_async(_prepare)(inputs)+++def _prepare(inputs: RunCheckSuiteInputs) -> PreparedSuite:+ checks = _select_checks(inputs) if is_data_quality_checks_enabled_for_team_id(inputs.team_id) else []+ suite_run = _suite_run(inputs)++ check_ids = [str(check_id) for check_id in checks]+ batches = [check_ids[start : start + CHECKS_PER_BATCH] for start in range(0, len(check_ids), CHECKS_PER_BATCH)]+ LOGGER.info("Prepared check suite", suite_run_id=str(suite_run.id), checks=len(check_ids), batches=len(batches))+ return PreparedSuite(suite_run_id=str(suite_run.id), batches=batches)+++def _suite_run(inputs: RunCheckSuiteInputs) -> DataQualitySuiteRun:+ """Adopt the row the API already created, or make one for a trigger that had nobody to hand it to.++ Keyed on ``workflow_id`` so a retry is idempotent: an attempt that commits the row and then dies+ before Temporal records its result must adopt that row on the next attempt, not strand an orphan+ that nothing ever finalizes.+ """+ info = activity.info()+ runs = DataQualitySuiteRun.objects.for_team(inputs.team_id)+ if inputs.suite_run_id:+ suite_run = runs.get(id=inputs.suite_run_id)+ suite_run.workflow_run_id = info.workflow_run_id or ""+ suite_run.save(update_fields=["workflow_run_id", "updated_at"])+ return suite_run++ if info.workflow_id:+ existing = runs.filter(workflow_id=info.workflow_id).first()+ if existing is not None:+ return existing++ return runs.create(+ team_id=inputs.team_id,+ trigger=inputs.trigger,+ created_by_id=inputs.created_by_id,+ data_modeling_job_id=inputs.data_modeling_job_id,+ workflow_id=info.workflow_id or "",+ workflow_run_id=info.workflow_run_id or "",+ started_at=datetime.now(UTC),+ **_single_subject_fields(inputs),+ )+++def _single_subject_fields(inputs: RunCheckSuiteInputs) -> dict[str, str]:+ """The subject columns to record, empty when the run spans more than one subject.++ Leaving them out lets the model's own column defaults stand, which is what "this run has no one+ subject" looks like on the row.+ """+ if len(inputs.saved_query_ids) == 1 and not inputs.table_ids:+ return {"subject_type": SubjectType.VIEW, "subject_uuid": inputs.saved_query_ids[0]}+ if len(inputs.table_ids) == 1 and not inputs.saved_query_ids:+ return {"subject_type": SubjectType.TABLE, "subject_uuid": inputs.table_ids[0]}+ return {}+++def _select_checks(inputs: RunCheckSuiteInputs) -> list[str]:+ runnable = DataQualityCheck.objects.for_team(inputs.team_id).filter(enabled=True, deleted=False)++ if inputs.check_ids:+ runnable = runnable.filter(id__in=inputs.check_ids)+ else:+ saved_query_ids = list(inputs.saved_query_ids)+ if inputs.node_ids:+ saved_query_ids += data_modeling_facade.get_saved_query_ids_for_nodes(inputs.team_id, inputs.node_ids)+ if not saved_query_ids and not inputs.table_ids:+ return []+ subject_filter = models.Q(saved_query_id__in=saved_query_ids)+ if inputs.table_ids:+ subject_filter |= models.Q(table_id__in=inputs.table_ids)+ runnable = runnable.filter(subject_filter)++ return [str(check_id) for check_id in runnable.values_list("id", flat=True)]diff --git a/products/data_quality/backend/temporal/activities/run_check_batch.py b/products/data_quality/backend/temporal/activities/run_check_batch.pynew file mode 100644index 000000000000..0cb7a8d4d343--- /dev/null+++ b/products/data_quality/backend/temporal/activities/run_check_batch.py@@ -0,0 +1,54 @@+from collections import Counter++from asgiref.sync import sync_to_async+from temporalio import activity++from posthog.models.team import Team+from posthog.temporal.common.heartbeat import Heartbeater+from posthog.temporal.common.logger import get_logger++from ...facade.enums import CheckRunStatus, CheckSeverity+from ...logic.runner import run_check+from ...models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from ..contracts import BatchOutcome, RunCheckBatchInputs++LOGGER = get_logger(__name__)+++async def run_check_batch_activity(inputs: RunCheckBatchInputs) -> BatchOutcome:+ async with Heartbeater():+ return await sync_to_async(_run_batch)(inputs)+++def _run_batch(inputs: RunCheckBatchInputs) -> BatchOutcome:+ team = Team.objects.get(id=inputs.team_id)+ suite_run = DataQualitySuiteRun.objects.for_team(inputs.team_id).get(id=inputs.suite_run_id)+ checks = DataQualityCheck.objects.for_team(inputs.team_id).filter(+ id__in=inputs.check_ids, enabled=True, deleted=False+ )++ DataQualityCheckRun.objects.for_team(inputs.team_id).filter(+ suite_run=suite_run, quality_check_id__in=inputs.check_ids+ ).delete()++ counts: Counter[str] = Counter()+ failed_blocking = 0+ newly_failing: list[str] = []+ for check in checks:+ result = run_check(check, suite_run, team)+ counts[result.status] += 1+ if result.status is CheckRunStatus.FAILED and check.severity == CheckSeverity.ERROR:+ failed_blocking += 1+ if result.became_failing:+ newly_failing.append(str(check.id))++ LOGGER.info("Ran check batch", suite_run_id=inputs.suite_run_id, checks=len(inputs.check_ids))+ return BatchOutcome(+ passed=counts[CheckRunStatus.PASSED],+ failed=counts[CheckRunStatus.FAILED],+ errored=counts[CheckRunStatus.ERRORED],+ skipped=counts[CheckRunStatus.SKIPPED],+ failed_blocking=failed_blocking,+ newly_failing_check_ids=newly_failing,+ )diff --git a/products/data_quality/backend/temporal/contracts.py b/products/data_quality/backend/temporal/contracts.pynew file mode 100644index 000000000000..f821fc8eda25--- /dev/null+++ b/products/data_quality/backend/temporal/contracts.py@@ -0,0 +1,93 @@+"""Inputs and outputs crossing the workflow/activity boundary.++Flat, JSON-friendly dataclasses: workflow inputs also arrive from the management-command CLI as a+single JSON object, so nested dataclasses would not survive ``parse_inputs``.+"""++import dataclasses++from posthog.dataclasses import frozen++from ..facade.enums import SuiteRunStatus, SuiteRunTrigger+++@frozen+class RunCheckSuiteInputs:+ """What to run. Exactly one selector is expected; a suite with no matching checks is not an error.++ ``node_ids`` is the materialization path: the DAG workflow knows nodes, not saved queries, and+ the mapping is resolved inside the prepare activity so the workflow stays deterministic.+ ``table_ids`` is the source-sync path, keyed on the table so it works with or without a DAG.+ """++ team_id: int+ trigger: SuiteRunTrigger+ saved_query_ids: list[str] = dataclasses.field(default_factory=list)+ table_ids: list[str] = dataclasses.field(default_factory=list)+ check_ids: list[str] = dataclasses.field(default_factory=list)+ node_ids: list[str] = dataclasses.field(default_factory=list)+ suite_run_id: str | None = None+ data_modeling_job_id: str | None = None+ created_by_id: int | None = None+++@frozen+class MaterializationGateInputs:+ team_id: int+ node_ids: list[str]+++@frozen+class PreparedSuite:+ suite_run_id: str+ batches: list[list[str]]+++@frozen+class RunCheckBatchInputs:+ team_id: int+ suite_run_id: str+ check_ids: list[str]+++@frozen+class BatchOutcome:+ passed: int = 0+ failed: int = 0+ errored: int = 0+ skipped: int = 0+ failed_blocking: int = 0+ newly_failing_check_ids: list[str] = dataclasses.field(default_factory=list)+++@frozen+class FinalizeCheckSuiteInputs:+ team_id: int+ suite_run_id: str+ outcomes: list[BatchOutcome]+++@frozen+class MarkSuiteFailedInputs:+ team_id: int+ suite_run_id: str+ error: str+++@frozen+class CleanupOutcome:+ compiled_queries_cleared: int = 0+ check_runs_deleted: int = 0+ suite_runs_deleted: int = 0+ stale_suites_failed: int = 0+++@frozen+class CheckSuiteResult:+ suite_run_id: str+ status: SuiteRunStatus+ checks_passed: int = 0+ checks_failed: int = 0+ checks_errored: int = 0+ checks_skipped: int = 0+ checks_failed_blocking: int = 0diff --git a/products/data_quality/backend/temporal/schedule.py b/products/data_quality/backend/temporal/schedule.pynew file mode 100644index 000000000000..ea4268592add--- /dev/null+++ b/products/data_quality/backend/temporal/schedule.py@@ -0,0 +1,42 @@+"""Cron schedules for data quality checks, registered on the data-modeling task queue."""++import datetime as dt++from django.conf import settings++from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleSpec,+)++from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule++CLEANUP_SCHEDULE_ID = "cleanup-data-quality-check-runs-schedule"+++async def create_cleanup_data_quality_check_runs_schedule(client: Client) -> None:+ await _upsert(+ client,+ CLEANUP_SCHEDULE_ID,+ Schedule(+ action=ScheduleActionStartWorkflow(+ "cleanup-data-quality-check-runs",+ id=CLEANUP_SCHEDULE_ID,+ task_queue=settings.DATA_MODELING_TASK_QUEUE,+ execution_timeout=dt.timedelta(minutes=45),+ ),+ spec=ScheduleSpec(cron_expressions=["30 4 * * *"]),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ ),+ )+++async def _upsert(client: Client, schedule_id: str, schedule: Schedule) -> None:+ if await a_schedule_exists(client, schedule_id):+ await a_update_schedule(client, schedule_id, schedule)+ else:+ await a_create_schedule(client, schedule_id, schedule, trigger_immediately=False)diff --git a/products/data_quality/backend/temporal/workflows/cleanup.py b/products/data_quality/backend/temporal/workflows/cleanup.pynew file mode 100644index 000000000000..fb2ba1a2a6df--- /dev/null+++ b/products/data_quality/backend/temporal/workflows/cleanup.py@@ -0,0 +1,26 @@+import datetime as dt++from temporalio import workflow+from temporalio.common import RetryPolicy++from posthog.temporal.common.base import PostHogWorkflow++from ..activities.cleanup import cleanup_check_runs_activity+from ..contracts import CleanupOutcome++[email protected](name="cleanup-data-quality-check-runs")+class CleanupCheckRunsWorkflow(PostHogWorkflow):+ """Daily retention sweep over check-run history."""++ @staticmethod+ def parse_inputs(inputs: list[str]) -> None:+ return None++ @workflow.run+ async def run(self) -> CleanupOutcome:+ return await workflow.execute_activity(+ cleanup_check_runs_activity,+ start_to_close_timeout=dt.timedelta(minutes=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )diff --git a/products/data_quality/backend/temporal/workflows/run_check_suite.py b/products/data_quality/backend/temporal/workflows/run_check_suite.pynew file mode 100644index 000000000000..9170b8421082--- /dev/null+++ b/products/data_quality/backend/temporal/workflows/run_check_suite.py@@ -0,0 +1,89 @@+import asyncio+import datetime as dt++from temporalio import workflow+from temporalio.common import RetryPolicy++from posthog.temporal.common.base import PostHogWorkflow++from ..activities.finalize_check_suite import (+ finalize_check_suite_activity,+ mark_check_suite_empty_activity,+ mark_check_suite_failed_activity,+)+from ..activities.prepare_check_suite import prepare_check_suite_activity+from ..activities.run_check_batch import run_check_batch_activity+from ..contracts import (+ BatchOutcome,+ CheckSuiteResult,+ FinalizeCheckSuiteInputs,+ MarkSuiteFailedInputs,+ PreparedSuite,+ RunCheckBatchInputs,+ RunCheckSuiteInputs,+)++MAX_CONCURRENT_BATCHES = 4++[email protected](name="data-quality-run-suite")+class RunCheckSuiteWorkflow(PostHogWorkflow):+ """Run a batch of data quality checks and record a report.++ Individual check failures are data, not workflow failures: a suite completes as long as it+ could load its checks, whatever they found.+ """++ inputs_cls = RunCheckSuiteInputs++ @workflow.run+ async def run(self, inputs: RunCheckSuiteInputs) -> CheckSuiteResult:+ suite_run_id = inputs.suite_run_id+ try:+ prepared: PreparedSuite = await workflow.execute_activity(+ prepare_check_suite_activity,+ inputs,+ start_to_close_timeout=dt.timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ suite_run_id = prepared.suite_run_id++ if not prepared.batches:+ return await workflow.execute_activity(+ mark_check_suite_empty_activity,+ FinalizeCheckSuiteInputs(team_id=inputs.team_id, suite_run_id=prepared.suite_run_id, outcomes=[]),+ start_to_close_timeout=dt.timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )++ outcomes = await self._run_batches(inputs.team_id, prepared)+ return await workflow.execute_activity(+ finalize_check_suite_activity,+ FinalizeCheckSuiteInputs(team_id=inputs.team_id, suite_run_id=prepared.suite_run_id, outcomes=outcomes),+ start_to_close_timeout=dt.timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ except Exception as error:+ if suite_run_id:+ await workflow.execute_activity(+ mark_check_suite_failed_activity,+ MarkSuiteFailedInputs(team_id=inputs.team_id, suite_run_id=suite_run_id, error=str(error)),+ start_to_close_timeout=dt.timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ raise++ async def _run_batches(self, team_id: int, prepared: PreparedSuite) -> list[BatchOutcome]:+ semaphore = asyncio.Semaphore(MAX_CONCURRENT_BATCHES)++ async def _run(check_ids: list[str]) -> BatchOutcome:+ async with semaphore:+ return await workflow.execute_activity(+ run_check_batch_activity,+ RunCheckBatchInputs(team_id=team_id, suite_run_id=prepared.suite_run_id, check_ids=check_ids),+ start_to_close_timeout=dt.timedelta(minutes=30),+ heartbeat_timeout=dt.timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )++ return list(await asyncio.gather(*[_run(batch) for batch in prepared.batches]))diff --git a/products/data_quality/backend/tests/test_cleanup.py b/products/data_quality/backend/tests/test_cleanup.pynew file mode 100644index 000000000000..f31afb64b2fc--- /dev/null+++ b/products/data_quality/backend/tests/test_cleanup.py@@ -0,0 +1,135 @@+from datetime import UTC, datetime, timedelta+from uuid import uuid4++from posthog.test.base import BaseTest++from parameterized import parameterized++from products.data_quality.backend.facade.enums import (+ CheckRunStatus,+ CheckType,+ SubjectType,+ SuiteRunStatus,+ SuiteRunTrigger,+)+from products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from products.data_quality.backend.temporal.activities.cleanup import (+ CHECK_RUN_RETENTION_DAYS,+ COMPILED_QUERY_RETENTION_DAYS,+ STALE_SUITE_HOURS,+ SUITE_RUN_RETENTION_DAYS,+ _cleanup,+)+++class TestRetentionSweep(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.check = DataQualityCheck.objects.for_team(self.team.id).create(+ team=self.team,+ subject_type=SubjectType.VIEW,+ saved_query_id=uuid4(),+ subject_name="orders",+ check_type=CheckType.NOT_NULL,+ column_name="customer_id",+ fingerprint=uuid4().hex,+ )++ def _suite(self, *, age_days: float = 0, status: SuiteRunStatus = SuiteRunStatus.COMPLETED) -> DataQualitySuiteRun:+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger=SuiteRunTrigger.MANUAL, status=status+ )+ return self._age(DataQualitySuiteRun, suite, age_days)++ def _run(self, *, age_days: float = 0, **kwargs) -> DataQualityCheckRun:+ defaults = {+ "team": self.team,+ "quality_check": self.check,+ "suite_run": kwargs.pop("suite_run", None) or self._suite(),+ "subject_type": SubjectType.VIEW,+ "subject_uuid": uuid4(),+ "subject_name": "orders",+ "check_type": CheckType.NOT_NULL,+ "check_fingerprint": uuid4().hex,+ "status": CheckRunStatus.PASSED,+ }+ run = DataQualityCheckRun.objects.for_team(self.team.id).create(**{**defaults, **kwargs})+ return self._age(DataQualityCheckRun, run, age_days)++ def _age(self, model, instance, age_days: float):+ created_at = datetime.now(UTC) - timedelta(days=age_days)+ model.objects.unscoped().filter(id=instance.id).update(created_at=created_at)+ instance.refresh_from_db()+ return instance++ @parameterized.expand(+ [+ ("inside_the_window", COMPILED_QUERY_RETENTION_DAYS - 1, "SELECT 1"),+ ("past_the_window", COMPILED_QUERY_RETENTION_DAYS + 1, ""),+ ]+ )+ def test_the_compiled_query_is_cleared_only_once_it_ages_out(self, _name, age_days, expected) -> None:+ run = self._run(age_days=age_days, compiled_query="SELECT 1")++ _cleanup()++ run.refresh_from_db()+ assert run.compiled_query == expected++ def test_an_aged_run_survives_while_it_is_the_newest_for_its_check(self) -> None:+ run = self._run(age_days=CHECK_RUN_RETENTION_DAYS + 1)++ outcome = _cleanup()++ assert outcome.check_runs_deleted == 0+ assert DataQualityCheckRun.objects.unscoped().filter(id=run.id).exists()++ def test_an_aged_run_is_deleted_once_a_newer_one_exists_for_the_same_check(self) -> None:+ aged = self._run(age_days=CHECK_RUN_RETENTION_DAYS + 1)+ newest = self._run()++ _cleanup()++ surviving = set(DataQualityCheckRun.objects.unscoped().values_list("id", flat=True))+ assert surviving == {newest.id}+ assert aged.id not in surviving++ def test_an_aged_run_whose_check_is_gone_ages_out_unconditionally(self) -> None:+ orphan = self._run(age_days=CHECK_RUN_RETENTION_DAYS + 1, quality_check=None)++ _cleanup()++ assert not DataQualityCheckRun.objects.unscoped().filter(id=orphan.id).exists()++ def test_an_aged_suite_survives_while_a_check_run_still_points_at_it(self) -> None:+ suite = self._suite(age_days=SUITE_RUN_RETENTION_DAYS + 1)+ self._run(suite_run=suite)++ outcome = _cleanup()++ assert outcome.suite_runs_deleted == 0+ assert DataQualitySuiteRun.objects.unscoped().filter(id=suite.id).exists()++ def test_an_aged_suite_with_nothing_pointing_at_it_is_deleted(self) -> None:+ self._suite(age_days=SUITE_RUN_RETENTION_DAYS + 1)+ recent = self._suite(age_days=SUITE_RUN_RETENTION_DAYS - 1)++ outcome = _cleanup()++ assert outcome.suite_runs_deleted == 1+ assert set(DataQualitySuiteRun.objects.unscoped().values_list("id", flat=True)) == {recent.id}++ @parameterized.expand(+ [+ ("still_within_the_window", (STALE_SUITE_HOURS - 1) / 24, SuiteRunStatus.RUNNING),+ ("stopped_without_a_result", (STALE_SUITE_HOURS + 1) / 24, SuiteRunStatus.FAILED),+ ]+ )+ def test_a_running_suite_is_failed_once_it_is_stale(self, _name, age_days, expected_status) -> None:+ suite = self._suite(age_days=age_days, status=SuiteRunStatus.RUNNING)++ _cleanup()++ suite.refresh_from_db()+ assert suite.status == expected_status+ assert (suite.finished_at is not None) == (expected_status == SuiteRunStatus.FAILED)diff --git a/products/data_quality/backend/tests/test_run_check_suite.py b/products/data_quality/backend/tests/test_run_check_suite.pynew file mode 100644index 000000000000..d241f7427c4d--- /dev/null+++ b/products/data_quality/backend/tests/test_run_check_suite.py@@ -0,0 +1,261 @@+from uuid import uuid4++from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, patch++from asgiref.sync import async_to_sync+from parameterized import parameterized+from temporalio import workflow as temporal_workflow++from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.data_quality.backend.facade.enums import (+ CheckRunStatus,+ CheckType,+ SubjectType,+ SuiteRunStatus,+ SuiteRunTrigger,+)+from products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from products.data_quality.backend.temporal.activities.finalize_check_suite import _finalize+from products.data_quality.backend.temporal.activities.prepare_check_suite import _prepare+from products.data_quality.backend.temporal.activities.run_check_batch import _run_batch+from products.data_quality.backend.temporal.contracts import (+ BatchOutcome,+ CheckSuiteResult,+ FinalizeCheckSuiteInputs,+ PreparedSuite,+ RunCheckBatchInputs,+ RunCheckSuiteInputs,+)+from products.data_quality.backend.temporal.workflows.run_check_suite import RunCheckSuiteWorkflow++RUNNER_QUERY = "products.data_quality.backend.logic.runner.execute_hogql_query"+ACTIVITY_INFO = "products.data_quality.backend.temporal.activities.prepare_check_suite.activity.info"+PREPARE_FLAG = (+ "products.data_quality.backend.temporal.activities.prepare_check_suite.is_data_quality_checks_enabled_for_team_id"+)+++class _Response:+ def __init__(self, columns: list[str], row: list) -> None:+ self.columns = columns+ self.results = [row]+++class _ActivityInfo:+ workflow_id = "wf-1"+ workflow_run_id = "run-1"+++class TestCheckSuiteActivities(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.view = DataWarehouseSavedQuery.objects.create(team=self.team, name="orders", query={"kind": "HogQLQuery"})+ flag = patch(PREPARE_FLAG, return_value=True)+ flag.start()+ self.addCleanup(flag.stop)++ def _check(self, **kwargs) -> DataQualityCheck:+ defaults = {+ "team": self.team,+ "subject_type": SubjectType.VIEW,+ "saved_query_id": self.view.id,+ "subject_name": "orders",+ "check_type": CheckType.NOT_NULL,+ "column_name": "customer_id",+ "fingerprint": uuid4().hex,+ }+ return DataQualityCheck.objects.for_team(self.team.id).create(**{**defaults, **kwargs})++ def _prepare(self, **kwargs) -> PreparedSuite:+ inputs = RunCheckSuiteInputs(+ team_id=self.team.id,+ trigger=kwargs.pop("trigger", SuiteRunTrigger.MANUAL),+ saved_query_ids=kwargs.pop("saved_query_ids", [str(self.view.id)]),+ **kwargs,+ )+ with patch(ACTIVITY_INFO, return_value=_ActivityInfo()):+ return _prepare(inputs)++ def test_a_subject_with_no_checks_produces_no_batches(self) -> None:+ prepared = self._prepare()++ assert prepared.batches == []+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).get(id=prepared.suite_run_id)+ assert suite_run.subject_uuid == self.view.id++ def test_a_suite_spanning_several_subjects_records_none_of_them(self) -> None:+ other_view = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="refunds", query={"kind": "HogQLQuery"}+ )++ prepared = self._prepare(saved_query_ids=[str(self.view.id), str(other_view.id)])++ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).get(id=prepared.suite_run_id)+ assert suite_run.subject_uuid is None+ assert suite_run.subject_type == ""++ def test_disabled_and_deleted_checks_are_not_selected(self) -> None:+ runnable = self._check()+ self._check(enabled=False)+ self._check(deleted=True)++ prepared = self._prepare()++ assert prepared.batches == [[str(runnable.id)]]++ def test_table_checks_are_selected_by_table_ids(self) -> None:+ table_id = uuid4()+ on_table = self._check(saved_query_id=None, table_id=table_id, subject_type=SubjectType.TABLE)+ self._check()++ prepared = self._prepare(saved_query_ids=[], table_ids=[str(table_id)], trigger=SuiteRunTrigger.SOURCE_SYNC)++ assert prepared.batches == [[str(on_table.id)]]+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).get(id=prepared.suite_run_id)+ assert suite_run.subject_type == SubjectType.TABLE+ assert suite_run.subject_uuid == table_id++ def test_an_unflagged_org_prepares_an_empty_suite(self) -> None:+ self._check()++ with patch(PREPARE_FLAG, return_value=False):+ prepared = self._prepare()++ assert prepared.batches == []++ def test_a_batch_counts_each_outcome_and_records_a_run_per_check(self) -> None:+ passing = self._check()+ failing = self._check(column_name="total")+ erroring = self._check(check_type=CheckType.CUSTOM_SQL, column_name="", config={"query": "nonsense ((("})+ prepared = self._prepare()++ def _fake_query(query, team, query_type):+ failure_count = 4 if "total" in str(query.to_hogql()) else 0+ return _Response(["failure_count", "observed_value"], [failure_count, failure_count])++ with patch(RUNNER_QUERY, side_effect=_fake_query):+ outcome = _run_batch(+ RunCheckBatchInputs(+ team_id=self.team.id,+ suite_run_id=prepared.suite_run_id,+ check_ids=[str(passing.id), str(failing.id), str(erroring.id)],+ )+ )++ assert (outcome.passed, outcome.failed, outcome.errored) == (1, 1, 1)+ assert outcome.failed_blocking == 1+ assert outcome.newly_failing_check_ids == [str(failing.id)]+ runs = DataQualityCheckRun.objects.for_team(self.team.id).filter(suite_run_id=prepared.suite_run_id)+ assert runs.count() == 3+ assert runs.get(quality_check=erroring).status == CheckRunStatus.ERRORED++ def test_a_check_disabled_after_prepare_is_not_run(self) -> None:+ stays = self._check()+ disabled_later = self._check(column_name="total")+ prepared = self._prepare()++ DataQualityCheck.objects.for_team(self.team.id).filter(id=disabled_later.id).update(enabled=False)++ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [0, 0])):+ outcome = _run_batch(+ RunCheckBatchInputs(+ team_id=self.team.id,+ suite_run_id=prepared.suite_run_id,+ check_ids=[str(stays.id), str(disabled_later.id)],+ )+ )++ assert outcome.passed == 1+ runs = DataQualityCheckRun.objects.for_team(self.team.id).filter(suite_run_id=prepared.suite_run_id)+ assert list(runs.values_list("quality_check_id", flat=True)) == [stays.id]++ def test_finalize_sums_batch_outcomes_into_the_report(self) -> None:+ prepared = self._prepare()++ result = _finalize(+ FinalizeCheckSuiteInputs(+ team_id=self.team.id,+ suite_run_id=prepared.suite_run_id,+ outcomes=[BatchOutcome(passed=2, failed=1, failed_blocking=1), BatchOutcome(passed=3, errored=1)],+ )+ )++ assert (result.checks_passed, result.checks_failed, result.checks_errored) == (5, 1, 1)+ assert result.checks_failed_blocking == 1+ assert result.status == SuiteRunStatus.COMPLETED+++class TestRunCheckSuiteWorkflow(BaseTest):+ def _run(self, prepared: PreparedSuite, activity_results: list) -> tuple[CheckSuiteResult, AsyncMock]:+ execute_activity = AsyncMock(side_effect=[prepared, *activity_results])+ with patch.object(temporal_workflow, "execute_activity", new=execute_activity):+ result = async_to_sync(RunCheckSuiteWorkflow().run)(+ RunCheckSuiteInputs(team_id=self.team.id, trigger=SuiteRunTrigger.MANUAL)+ )+ return result, execute_activity++ def test_an_empty_suite_skips_the_batch_activities(self) -> None:+ empty = CheckSuiteResult(suite_run_id="s-1", status=SuiteRunStatus.EMPTY)++ result, execute_activity = self._run(PreparedSuite(suite_run_id="s-1", batches=[]), [empty])++ assert result.status == SuiteRunStatus.EMPTY+ started = [call.args[0].__name__ for call in execute_activity.await_args_list]+ assert started == ["prepare_check_suite_activity", "mark_check_suite_empty_activity"]++ def test_every_batch_is_run_and_folded_into_finalize(self) -> None:+ prepared = PreparedSuite(suite_run_id="s-1", batches=[["a"], ["b"]])+ completed = CheckSuiteResult(suite_run_id="s-1", status=SuiteRunStatus.COMPLETED)++ result, execute_activity = self._run(prepared, [BatchOutcome(passed=1), BatchOutcome(failed=1), completed])++ assert result.status == SuiteRunStatus.COMPLETED+ started = [call.args[0].__name__ for call in execute_activity.await_args_list]+ assert started == [+ "prepare_check_suite_activity",+ "run_check_batch_activity",+ "run_check_batch_activity",+ "finalize_check_suite_activity",+ ]+ finalize_inputs = execute_activity.await_args_list[-1].args[1]+ assert [outcome.passed for outcome in finalize_inputs.outcomes] == [1, 0]++ def test_a_failed_batch_marks_the_prepared_suite_failed_and_reraises(self) -> None:+ prepared = PreparedSuite(suite_run_id="s-1", batches=[["a"]])+ boom = RuntimeError("batch exhausted its retries")+ execute_activity = AsyncMock(side_effect=[prepared, boom, None])++ with patch.object(temporal_workflow, "execute_activity", new=execute_activity):+ with self.assertRaises(RuntimeError):+ async_to_sync(RunCheckSuiteWorkflow().run)(+ RunCheckSuiteInputs(team_id=self.team.id, trigger=SuiteRunTrigger.MANUAL)+ )++ started = [call.args[0].__name__ for call in execute_activity.await_args_list]+ assert started == [+ "prepare_check_suite_activity",+ "run_check_batch_activity",+ "mark_check_suite_failed_activity",+ ]+ assert execute_activity.await_args_list[-1].args[1].suite_run_id == "s-1"++ @parameterized.expand(+ [+ ("with_a_precreated_row", "pre-1", ["prepare_check_suite_activity", "mark_check_suite_failed_activity"]),+ ("without_a_row", None, ["prepare_check_suite_activity"]),+ ]+ )+ def test_a_prepare_failure_marks_only_a_precreated_row(self, _name, suite_run_id, expected_activities) -> None:+ execute_activity = AsyncMock(side_effect=[RuntimeError("prepare exhausted its retries"), None])++ with patch.object(temporal_workflow, "execute_activity", new=execute_activity):+ with self.assertRaises(RuntimeError):+ async_to_sync(RunCheckSuiteWorkflow().run)(+ RunCheckSuiteInputs(team_id=self.team.id, trigger=SuiteRunTrigger.MANUAL, suite_run_id=suite_run_id)+ )++ started = [call.args[0].__name__ for call in execute_activity.await_args_list]+ assert started == expected_activities+ if suite_run_id is not None:+ assert execute_activity.await_args_list[-1].args[1].suite_run_id == suite_run_iddiff --git a/products/data_quality/backend/tests/test_runner.py b/products/data_quality/backend/tests/test_runner.pynew file mode 100644index 000000000000..9900c1ffcd01--- /dev/null+++ b/products/data_quality/backend/tests/test_runner.py@@ -0,0 +1,177 @@+from uuid import uuid4++from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.clickhouse.query_tagging import Feature, Product, QueryTags, get_query_tags++from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.data_quality.backend.facade.enums import (+ CheckRunStatus,+ CheckSeverity,+ CheckType,+ SubjectStatus,+ SubjectType,+ SuiteRunTrigger,+)+from products.data_quality.backend.logic.runner import run_check+from products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun++RUNNER_QUERY = "products.data_quality.backend.logic.runner.execute_hogql_query"+++class _Response:+ def __init__(self, columns: list[str], row: list) -> None:+ self.columns = columns+ self.results = [row]+++class TestCheckRunner(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.view = DataWarehouseSavedQuery.objects.create(team=self.team, name="orders", query={"kind": "HogQLQuery"})+ self.suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger=SuiteRunTrigger.MANUAL+ )++ def _check(self, **kwargs) -> DataQualityCheck:+ defaults = {+ "team": self.team,+ "subject_type": SubjectType.VIEW,+ "saved_query_id": self.view.id,+ "subject_name": "orders",+ "check_type": CheckType.NOT_NULL,+ "column_name": "customer_id",+ "fingerprint": uuid4().hex,+ }+ return DataQualityCheck.objects.for_team(self.team.id).create(**{**defaults, **kwargs})++ @parameterized.expand(+ [+ ("no_failing_rows", 0, CheckRunStatus.PASSED),+ ("failing_rows", 7, CheckRunStatus.FAILED),+ ]+ )+ def test_zero_failing_rows_passes(self, _name, failure_count: int, expected: CheckRunStatus) -> None:+ check = self._check()+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [failure_count, 7])):+ outcome = run_check(check, self.suite_run, self.team)++ assert outcome.status == expected+ assert outcome.failed_row_count == failure_count++ @parameterized.expand(+ [+ ("within_bounds", {"min": 1, "max": 100}, 50, CheckRunStatus.PASSED),+ ("below_min", {"min": 10}, 5, CheckRunStatus.FAILED),+ ("above_max", {"max": 10}, 5000, CheckRunStatus.FAILED),+ ("on_the_boundary", {"min": 5, "max": 5}, 5, CheckRunStatus.PASSED),+ ]+ )+ def test_row_count_compares_the_observed_count_to_bounds(+ self, _name, config: dict, observed: int, expected: CheckRunStatus+ ) -> None:+ check = self._check(check_type=CheckType.ROW_COUNT, column_name="", config=config)+ with patch(RUNNER_QUERY, return_value=_Response(["observed_value"], [observed])):+ outcome = run_check(check, self.suite_run, self.team)++ assert outcome.status == expected+ assert outcome.failed_row_count is None+ assert outcome.observed_value == observed++ def test_a_broken_check_is_recorded_as_errored_rather_than_raised(self) -> None:+ check = self._check(check_type=CheckType.CUSTOM_SQL, column_name="", config={"query": "not a query at all"})++ outcome = run_check(check, self.suite_run, self.team)++ assert outcome.status == CheckRunStatus.ERRORED+ run = DataQualityCheckRun.objects.for_team(self.team.id).get(quality_check=check)+ assert run.status == CheckRunStatus.ERRORED+ assert run.error++ def test_a_gone_subject_is_skipped_and_marks_the_check_orphaned(self) -> None:+ check = self._check()+ self.view.soft_delete()++ outcome = run_check(check, self.suite_run, self.team)++ check.refresh_from_db()+ assert outcome.status == CheckRunStatus.SKIPPED+ assert check.subject_status == SubjectStatus.ORPHANED++ def test_a_hard_deleted_subject_is_skipped_without_a_history_row(self) -> None:+ check = self._check(saved_query_id=None)++ outcome = run_check(check, self.suite_run, self.team)++ check.refresh_from_db()+ assert outcome.status == CheckRunStatus.SKIPPED+ assert check.subject_status == SubjectStatus.ORPHANED+ assert not DataQualityCheckRun.objects.for_team(self.team.id).filter(quality_check=check).exists()++ def test_a_renamed_subject_heals_the_denormalized_name(self) -> None:+ check = self._check()+ self.view.name = "orders_v2"+ self.view.save()++ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [0, 0])):+ run_check(check, self.suite_run, self.team)++ check.refresh_from_db()+ assert check.subject_name == "orders_v2"++ def test_observed_value_is_recorded_on_a_pass(self) -> None:+ check = self._check(check_type=CheckType.FRESHNESS, column_name="created_at", config={"max_age_minutes": 60})+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [0, 42.0])):+ run_check(check, self.suite_run, self.team)++ run = DataQualityCheckRun.objects.for_team(self.team.id).get(quality_check=check)+ assert run.status == CheckRunStatus.PASSED+ assert run.observed_value == 42.0++ def test_the_check_query_is_tagged_with_this_product_and_the_check_it_came_from(self) -> None:+ check = self._check()+ captured: list[QueryTags] = []++ def capture(*args, **kwargs) -> _Response:+ captured.append(get_query_tags())+ return _Response(["failure_count", "observed_value"], [0, 0])++ with patch(RUNNER_QUERY, side_effect=capture):+ run_check(check, self.suite_run, self.team)++ tags = captured[0]+ assert (tags.product, tags.feature) == (Product.DATA_QUALITY, Feature.DATA_QUALITY_CHECK)+ assert tags.data_quality_check_id == str(check.id)+ assert tags.data_quality_check_type == CheckType.NOT_NULL+ assert tags.data_quality_subject_type == SubjectType.VIEW+ assert tags.data_quality_subject_id == str(self.view.id)++ def test_the_stored_query_selects_failing_rows(self) -> None:+ check = self._check()+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [3, 3])):+ run_check(check, self.suite_run, self.team)++ run = DataQualityCheckRun.objects.for_team(self.team.id).get(quality_check=check)+ assert run.compiled_query == "SELECT * FROM orders WHERE isNull(customer_id)"++ @parameterized.expand(+ [+ ("first_failure", "", CheckSeverity.ERROR, True),+ ("still_failing", CheckRunStatus.FAILED, CheckSeverity.ERROR, False),+ ("warn_severity", "", CheckSeverity.WARN, False),+ ("recovered_then_failed_again", CheckRunStatus.PASSED, CheckSeverity.ERROR, True),+ ]+ )+ def test_became_failing_marks_only_error_severity_transitions(+ self, _name, previous_status: str, severity: CheckSeverity, expected: bool+ ) -> None:+ check = self._check(last_status=previous_status, severity=severity)+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [3, 3])):+ outcome = run_check(check, self.suite_run, self.team)++ assert outcome.became_failing is expected+ check.refresh_from_db()+ assert check.last_status == CheckRunStatus.FAILEDdiff --git a/products/data_quality/backend/tests/test_triggers.py b/products/data_quality/backend/tests/test_triggers.pynew file mode 100644index 000000000000..391cc47a3b6f--- /dev/null+++ b/products/data_quality/backend/tests/test_triggers.py@@ -0,0 +1,74 @@+from uuid import uuid4++from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized++from products.data_modeling.backend.models import DAG, Node+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_quality.backend.facade.enums import CheckType, SubjectType+from products.data_quality.backend.logic.triggers import materialization_checks_needed, source_sync_checks_needed+from products.data_quality.backend.models import DataQualityCheck++TRIGGER_FLAG = "products.data_quality.backend.logic.triggers.is_data_quality_checks_enabled_for_team_id"+++class TestTriggerGates(BaseTest):+ """The gates the pipelines consult before spending a workflow on a suite."""++ def setUp(self) -> None:+ super().setUp()+ self.view = DataWarehouseSavedQuery.objects.create(team=self.team, name="orders", query="SELECT 1")+ self.node = Node.objects.create(+ team=self.team, dag=DAG.objects.create(team=self.team, name="dag"), saved_query=self.view, name="orders"+ )+ flag = patch(TRIGGER_FLAG, return_value=True)+ flag.start()+ self.addCleanup(flag.stop)++ def _check(self, **kwargs) -> DataQualityCheck:+ defaults = {+ "team": self.team,+ "subject_type": SubjectType.VIEW,+ "saved_query_id": self.view.id,+ "subject_name": "orders",+ "check_type": CheckType.NOT_NULL,+ "column_name": "customer_id",+ "fingerprint": uuid4().hex,+ }+ return DataQualityCheck.objects.for_team(self.team.id).create(**{**defaults, **kwargs})++ @parameterized.expand(+ [+ ("no_check_on_the_subject", None, True),+ ("a_disabled_check", {"enabled": False}, True),+ ("a_deleted_check", {"deleted": True}, True),+ ("a_runnable_check_but_the_flag_is_off", {}, False),+ ]+ )+ def test_no_suite_is_needed(self, _name, check_kwargs, flag_on) -> None:+ if check_kwargs is not None:+ self._check(**check_kwargs)++ with patch(TRIGGER_FLAG, return_value=flag_on):+ assert materialization_checks_needed(self.team.id, [str(self.node.id)]) is False++ def test_a_materialized_node_with_a_runnable_check_needs_a_suite(self) -> None:+ self._check()++ assert materialization_checks_needed(self.team.id, [str(self.node.id)]) is True++ def test_a_node_without_a_saved_query_needs_no_suite(self) -> None:+ self._check()+ source_node = Node.objects.create(+ team=self.team, dag=DAG.objects.create(team=self.team, name="other"), name="raw_events"+ )++ assert materialization_checks_needed(self.team.id, [str(source_node.id)]) is False++ def test_a_synced_table_with_a_runnable_check_needs_a_suite(self) -> None:+ table_id = uuid4()+ self._check(saved_query_id=None, table_id=table_id, subject_type=SubjectType.TABLE)++ assert source_sync_checks_needed(self.team.id, table_id) is Truediff --git a/products/warehouse_sources/backend/facade/hooks.py b/products/warehouse_sources/backend/facade/hooks.pyindex b7cb7847402a..b63621c4f97c 100644--- a/products/warehouse_sources/backend/facade/hooks.py+++ b/products/warehouse_sources/backend/facade/hooks.py@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_hPersonPropertySyncRunRecord,PersonPropertySyncSource,person_property_projection_for,+ register_data_quality_checks_gate,register_emit_signals_gate,register_engineering_analytics_view_sync,register_person_property_projection,@@ -28,6 +29,7 @@ __all__ = ["PersonPropertySyncRunRecord","PersonPropertySyncSource","person_property_projection_for",+ "register_data_quality_checks_gate","register_emit_signals_gate","register_engineering_analytics_view_sync","register_person_property_projection",diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py b/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.pyindex 8581761a30fc..4fcdcb8df026 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py@@ -232,6 +232,46 @@ class PersonPropertyBackfillActivityInputs:}+# --- Data-quality checks gate ---------------------------------------------------------++DataQualityChecksGate = Callable[[int, "str | uuid.UUID"], bool]+_data_quality_checks_gate: Optional[DataQualityChecksGate] = None+++def register_data_quality_checks_gate(fn: DataQualityChecksGate) -> None:+ global _data_quality_checks_gate+ _data_quality_checks_gate = fn+++def data_quality_checks_needed_for(team_id: int, table_id: "str | uuid.UUID | None") -> bool:+ if _data_quality_checks_gate is None or table_id is None:+ return False+ return _data_quality_checks_gate(team_id, table_id)++[email protected](frozen=True)+class DataQualitySuiteTriggerInputs:+ """Payload the import pipeline sends to the data-quality suite workflow.++ Field names mirror data_quality's ``RunCheckSuiteInputs`` (the workflow is started by+ registered name, so nothing here imports that product); omitted selector fields fall back to+ the workflow input's defaults. ``trigger`` stays a plain string for the same reason: the+ ``SuiteRunTrigger`` enum it decodes into lives on the other side of a one-way dependency.+ """++ team_id: int+ trigger: str+ table_ids: list[str]++ @property+ def properties_to_log(self) -> dict[str, Any]:+ return {+ "team_id": self.team_id,+ "trigger": self.trigger,+ "table_ids": self.table_ids,+ }++# --- Person-property sync run recorder ------------------------------------------------# The sync/backfill activities (owned by warehouse_sources) persist each run's funnel counts so the# customer_analytics UI can show run history and affected-person counts. Recording is inverted thediff --git a/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py b/products/warehouse_sources/backend/temporal/data_imports/post_import_job.pyindex 57a75cb8ea1c..1d6aa798de7c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py@@ -40,7 +40,9 @@ from products.managed_warehouse.backend.facade.temporal import (from products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (+ DataQualitySuiteTriggerInputs,EmitSignalsActivityInputs,+ data_quality_checks_needed_for,emit_signals_enabled_for,)from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.calculate_table_size import (@@ -108,6 +110,7 @@ class PostImportContext:enrichment_needed: bool = Falsestatistics_needed: bool = Falsesteps: list[str] | None = None+ table_id: str | None = None@dataclasses.dataclass(frozen=True)@@ -166,12 +169,14 @@ def _always(gate: PostImportGateContext) -> bool:return True+def _data_quality_gate(gate: PostImportGateContext) -> bool:+ return data_quality_checks_needed_for(gate.team_id, gate.schema.table_id)++async def _start_emit_signals(inputs: PostImportWorkflowInputs, ctx: PostImportContext) -> None:# The gate guarantees these when the key is recorded; the guard is type narrowing only.if ctx.source_type is None or ctx.schema_name is None:return- # Started by registered workflow name (not class import) so warehouse_sources- # doesn't import the signals product, which depends on it. See external_product_hooks.try:await workflow.start_child_workflow("emit-data-import-signals",@@ -267,11 +272,35 @@ async def _start_ducklake_copy(inputs: PostImportWorkflowInputs, ctx: PostImport)+async def _start_data_quality_checks(inputs: PostImportWorkflowInputs, ctx: PostImportContext) -> None:+ if ctx.table_id is None:+ return+ try:+ await workflow.start_child_workflow(+ "data-quality-run-suite",+ DataQualitySuiteTriggerInputs(+ team_id=inputs.team_id,+ trigger="source_sync",+ table_ids=[ctx.table_id],+ ),+ id=f"data-quality-source-sync-{inputs.schema_id}-{inputs.job_id}",+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ task_queue=settings.DATA_MODELING_TASK_QUEUE,+ parent_close_policy=ParentClosePolicy.ABANDON,+ )+ except WorkflowAlreadyStartedError:+ workflow.logger.info(+ "Data quality checks already started for this sync, skipping",+ extra={"schema_id": inputs.schema_id, "job_id": inputs.job_id},+ )++EMIT_SIGNALS_STEP = "emit-signals"SEMANTIC_ENRICHMENT_STEP = "semantic-enrichment"TABLE_STATISTICS_STEP = "table-statistics"TABLE_SIZE_STEP = "table-size"DUCKLAKE_COPY_STEP = "ducklake-copy"+DATA_QUALITY_CHECKS_STEP = "data-quality-checks"# Ordered registry of every post-import step. This is the future registration point for# product-owned steps (external_product_hooks-style), so entries stay self-contained:@@ -282,6 +311,7 @@ POST_IMPORT_STEPS: tuple[PostImportStep, ...] = (PostImportStep(key=TABLE_STATISTICS_STEP, enabled=_statistics_gate, start=_start_table_statistics),PostImportStep(key=TABLE_SIZE_STEP, enabled=_always, start=_start_table_size),PostImportStep(key=DUCKLAKE_COPY_STEP, enabled=_always, start=_start_ducklake_copy),+ PostImportStep(key=DATA_QUALITY_CHECKS_STEP, enabled=_data_quality_gate, start=_start_data_quality_checks),)_STEP_BY_KEY = {step.key: step for step in POST_IMPORT_STEPS}@@ -364,6 +394,7 @@ def resolve_post_import_context_activity(inputs: PostImportWorkflowInputs) -> Poenrichment_needed=SEMANTIC_ENRICHMENT_STEP in steps,statistics_needed=TABLE_STATISTICS_STEP in steps,steps=steps,+ table_id=str(schema.table_id) if schema.table_id else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.pyindex 64fca1905cc0..06a3b3baef3a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py@@ -334,6 +334,31 @@ async def test_post_import_workflow_runs_moved_steps(gates_on: bool, steps_mode:assert any(c.startswith("ducklake-copy-data-imports-") for c in child_ids)+async def test_each_completed_sync_gets_its_own_data_quality_suite():+ from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (+ PostImportContext,+ PostImportWorkflowInputs,+ _start_data_quality_checks,+ )++ schema_id, table_id = str(uuid.uuid4()), str(uuid.uuid4())+ ctx = PostImportContext(table_id=table_id)++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.post_import_job.workflow.start_child_workflow",+ new_callable=mock.AsyncMock,+ ) as mock_start_child:+ for job_id in (_JOB_ID, str(uuid.uuid4())):+ await _start_data_quality_checks(+ PostImportWorkflowInputs(team_id=1, job_id=job_id, schema_id=schema_id, source_id=str(uuid.uuid4())),+ ctx,+ )++ child_ids = [call.kwargs["id"] for call in mock_start_child.call_args_list]+ assert len(set(child_ids)) == 2+ assert all(child_id.startswith(f"data-quality-source-sync-{schema_id}-") for child_id in child_ids)++@pytest.fixturedef _no_close_old_connections():# The activity reconnects stale worker connections; under pytest-django that would