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.

fix(data-quality): explain blocked materializations (#108632)

Jovan Sakovic0147733caa22
diff --git a/posthog/temporal/data_modeling/activities/quality_block_materialization.py b/posthog/temporal/data_modeling/activities/quality_block_materialization.py
index 25ff6413ef83..5d5325b064d9 100644
--- a/posthog/temporal/data_modeling/activities/quality_block_materialization.py
+++ b/posthog/temporal/data_modeling/activities/quality_block_materialization.py
@@ -34,22 +34,43 @@ class QualityBlockMaterializationInputs:
"dag_id": self.dag_id,
"job_id": self.job_id,
"blocking_failures": self.blocking_failures,
+ "suite_run_id": self.suite_run_id,
}
-def _quality_error(inputs: QualityBlockMaterializationInputs) -> str:
- checks = "check" if inputs.blocking_failures == 1 else "checks"
+def _quality_error(inputs: QualityBlockMaterializationInputs, saved_query_id: str | None) -> str:
+ details = None
+ if inputs.suite_run_id is not None and saved_query_id is not None:
+ try:
+ details = data_quality_facade.materialization_failure_summary(
+ inputs.team_id,
+ suite_run_id=inputs.suite_run_id,
+ data_modeling_job_id=inputs.job_id,
+ saved_query_id=saved_query_id,
+ blocking_failures=inputs.blocking_failures,
+ )
+ except Exception:
+ LOGGER.exception("Could not summarize materialization data quality failures")
+
+ if details is None:
+ checks = "check" if inputs.blocking_failures == 1 else "checks"
+ return (
+ f"{QUALITY_BLOCKED_ERROR_PREFIX} {inputs.blocking_failures} data quality {checks} failed. "
+ "The previous version keeps serving until the checks pass."
+ )
+ if inputs.blocking_failures == 1:
+ return f"{QUALITY_BLOCKED_ERROR_PREFIX} {details}. The previous version keeps serving until the checks pass."
return (
- f"{QUALITY_BLOCKED_ERROR_PREFIX} {inputs.blocking_failures} data quality {checks} failed. "
+ f"{QUALITY_BLOCKED_ERROR_PREFIX} {inputs.blocking_failures} data quality checks failed: {details}. "
"The previous version keeps serving until the checks pass."
)
@database_sync_to_async_pool
def _block_node_and_job(inputs: QualityBlockMaterializationInputs) -> None:
- error = _quality_error(inputs)
with transaction.atomic():
node = Node.objects.select_for_update().get(id=inputs.node_id, team_id=inputs.team_id, dag_id=inputs.dag_id)
+ error = _quality_error(inputs, str(node.saved_query_id) if node.saved_query_id else None)
update_node_system_properties(
node,
status=DataModelingJobStatus.FAILED,
diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.py
index b5de955f0acb..680bbdcb8ddc 100644
--- a/posthog/temporal/data_modeling/workflows/materialize_view.py
+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py
@@ -11,6 +11,7 @@ import temporalio.workflow
import temporalio.exceptions
from temporalio.exceptions import WorkflowAlreadyStartedError
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.data_modeling.activities import (
@@ -82,6 +83,7 @@ from products.warehouse_sources.backend.facade.hooks import (
# Covers every command the data quality feature adds here: the stage/audit/publish trio and the
# warn-mode suite child.
QUALITY_AUDIT_PATCH = "data-quality-audit-2026-08"
+QUALITY_BLOCK_SUITE_RUN_ID_PATCH = "data-quality-block-suite-run-id-2026-09"
ACCOUNT_PROPERTY_S3_SYNC_PATCH = "account-property-s3-sync-2026-08"
ACCOUNT_PROPERTY_STAGING_WORKFLOW_PATCH = "account-property-staging-workflow-2026-08"
@@ -168,6 +170,12 @@ class MaterializeViewWorkflowResult:
trino_materialized: bool | None = None
+@frozen
+class _StagedAuditVerdict:
+ suite_run_id: str | None
+ blocking_failures: int
+
+
@temporalio.workflow.defn(name="data-modeling-materialize-view")
class MaterializeViewWorkflow(PostHogWorkflow):
"""Temporal workflow to materialize a single view.
@@ -316,7 +324,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):
if temporalio.workflow.patched(QUALITY_AUDIT_PATCH)
else QUALITY_AUDIT_SKIP
)
- staged_verdict: int | None = None
+ staged_verdict: _StagedAuditVerdict | None = None
prepare_inputs = PrepareQueryableTableInputs(
team_id=inputs.team_id,
job_id=job_id,
@@ -336,7 +344,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):
staged_verdict = await self._staged_audit_verdict(
inputs, job_id, materialize_result, stage_result.staged_folder_path
)
- if staged_verdict:
+ if staged_verdict is not None and staged_verdict.blocking_failures:
await temporalio.workflow.execute_activity(
quality_block_materialization_activity,
QualityBlockMaterializationInputs(
@@ -344,7 +352,12 @@ class MaterializeViewWorkflow(PostHogWorkflow):
node_id=inputs.node_id,
dag_id=inputs.dag_id,
job_id=job_id,
- blocking_failures=staged_verdict,
+ blocking_failures=staged_verdict.blocking_failures,
+ suite_run_id=(
+ staged_verdict.suite_run_id
+ if temporalio.workflow.patched(QUALITY_BLOCK_SUITE_RUN_ID_PATCH)
+ else None
+ ),
),
start_to_close_timeout=dt.timedelta(minutes=5),
retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),
@@ -369,7 +382,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):
node_id=inputs.node_id,
rows_materialized=materialize_result.row_count,
duration_seconds=blocked_duration_seconds,
- quality_blocking_failures=staged_verdict,
+ quality_blocking_failures=staged_verdict.blocking_failures,
quality_audited=True,
trino_materialized=trino_materialized,
)
@@ -470,7 +483,9 @@ class MaterializeViewWorkflow(PostHogWorkflow):
node_id=inputs.node_id,
rows_materialized=materialize_result.row_count,
duration_seconds=duration_seconds,
- quality_blocking_failures=staged_verdict,
+ quality_blocking_failures=(
+ staged_verdict.blocking_failures if staged_verdict is not None else None
+ ),
quality_audited=quality_audited,
trino_materialized=trino_materialized,
)
@@ -553,8 +568,8 @@ class MaterializeViewWorkflow(PostHogWorkflow):
job_id: str,
materialize_result: MaterializeViewResult,
staged_folder_path: str,
- ) -> int | None:
- """The blocking-failure count, or None when the audit reached no verdict.
+ ) -> _StagedAuditVerdict | None:
+ """The suite ID and blocking-failure count, or None when the audit reached no verdict.
None still publishes, because a broken check pipeline is not a verdict on the data, and it
leaves the node to the DAG's sweep so the checks get another chance. Cancellation is not
@@ -585,7 +600,11 @@ class MaterializeViewWorkflow(PostHogWorkflow):
)
return None
if isinstance(result, dict):
- return int(result.get("checks_failed_blocking") or 0)
+ suite_run_id = result.get("suite_run_id")
+ return _StagedAuditVerdict(
+ suite_run_id=suite_run_id if isinstance(suite_run_id, str) else None,
+ blocking_failures=int(result.get("checks_failed_blocking") or 0),
+ )
return None
async def _start_suite_on_published_data(
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index a96b4ae74226..ef48aaa1f854 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -64,6 +64,15 @@ from products.data_modeling.backend.facade.models import (
Node,
NodeType,
)
+from products.data_quality.backend.facade.enums import (
+ CheckRunStatus,
+ CheckSeverity,
+ CheckType,
+ SubjectType,
+ SuiteRunStatus,
+ SuiteRunTrigger,
+)
+from products.data_quality.backend.facade.models import DataQualityCheckRun, DataQualitySuiteRun
from products.data_warehouse.backend.facade.api import CreateTableResult
from products.managed_warehouse.backend.facade.contracts import DuckLakeTableResult
from products.notifications.backend.facade.api import NotificationType, Priority, TargetType
@@ -571,21 +580,95 @@ class TestQualityBlockMaterializationActivity:
dag_id=str(adag.id),
job_id=str(job.id),
blocking_failures=2,
+ suite_run_id="suite-1",
)
- await activity_environment.run(quality_block_materialization_activity, inputs)
+ with unittest.mock.patch(
+ "posthog.temporal.data_modeling.activities.quality_block_materialization.data_quality_facade.materialization_failure_summary",
+ side_effect=RuntimeError("summary unavailable"),
+ ):
+ await activity_environment.run(quality_block_materialization_activity, inputs)
await database_sync_to_async(anode.refresh_from_db)()
await database_sync_to_async(job.refresh_from_db)()
system_props = anode.properties.get("system", {})
assert system_props["last_run_status"] == DataModelingJobStatus.FAILED
- assert "2 data quality checks failed" in system_props["last_run_error"]
+ expected_error = (
+ "Not published: 2 data quality checks failed. The previous version keeps serving until the checks pass."
+ )
+ assert system_props["last_run_error"] == expected_error
assert job.status == DataModelingJob.Status.FAILED
- assert "2 data quality checks failed" in job.error
+ assert job.error == expected_error
assert "suspended" not in system_props
await database_sync_to_async(job.delete)()
+ async def test_persists_the_safe_suite_summary_on_the_node_and_job(
+ self, activity_environment, ateam, anode, asaved_query, adag
+ ):
+ job = await _make_job(ateam, asaved_query, DataModelingJob.Status.RUNNING)
+ suite_run = await database_sync_to_async(
+ lambda: DataQualitySuiteRun.objects.for_team(ateam.pk).create(
+ team=ateam,
+ trigger=SuiteRunTrigger.MATERIALIZATION,
+ status=SuiteRunStatus.COMPLETED,
+ data_modeling_job_id=job.id,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=asaved_query.id,
+ )
+ )()
+ await database_sync_to_async(
+ lambda: DataQualityCheckRun.objects.for_team(ateam.pk).create(
+ team=ateam,
+ suite_run=suite_run,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=asaved_query.id,
+ subject_name="subject",
+ check_type=CheckType.ROW_COUNT,
+ check_fingerprint=uuid4().hex,
+ check_config={"min": 1_000},
+ check_severity=CheckSeverity.ERROR,
+ status=CheckRunStatus.FAILED,
+ observed_value=999,
+ )
+ )()
+ inputs = QualityBlockMaterializationInputs(
+ team_id=ateam.pk,
+ node_id=str(anode.id),
+ dag_id=str(adag.id),
+ job_id=str(job.id),
+ blocking_failures=1,
+ suite_run_id=str(suite_run.id),
+ )
+
+ await activity_environment.run(quality_block_materialization_activity, inputs)
+
+ await database_sync_to_async(anode.refresh_from_db)()
+ await database_sync_to_async(job.refresh_from_db)()
+ expected_error = "Not published: the row count is below its minimum. The previous version keeps serving until the checks pass."
+ assert anode.properties["system"]["last_run_error"] == expected_error
+ assert job.error == expected_error
+ await database_sync_to_async(job.delete)()
+
+ async def test_fails_the_node_when_the_job_no_longer_exists(self, activity_environment, ateam, anode, adag):
+ inputs = QualityBlockMaterializationInputs(
+ team_id=ateam.pk,
+ node_id=str(anode.id),
+ dag_id=str(adag.id),
+ job_id=str(uuid4()),
+ blocking_failures=1,
+ )
+
+ with pytest.raises(DataModelingJob.DoesNotExist):
+ await activity_environment.run(quality_block_materialization_activity, inputs)
+
+ await database_sync_to_async(anode.refresh_from_db)()
+ system_props = anode.properties.get("system", {})
+ assert system_props["last_run_status"] == DataModelingJobStatus.FAILED
+ assert system_props["last_run_error"] == (
+ "Not published: 1 data quality check failed. The previous version keeps serving until the checks pass."
+ )
+
class TestNodeSuspension:
async def test_suspends_for_engine_after_consecutive_failures(self, ateam, anode, asaved_query, adag):
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
index fff433f52a02..f2037fcdc257 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
@@ -24,9 +24,11 @@ from posthog.temporal.data_modeling.activities.enrich_view_semantics import Enri
from posthog.temporal.data_modeling.workflows.materialize_view import (
ACCOUNT_PROPERTY_S3_SYNC_PATCH,
ACCOUNT_PROPERTY_STAGING_WORKFLOW_PATCH,
+ QUALITY_BLOCK_SUITE_RUN_ID_PATCH,
TRINO_SHADOW_EXECUTION_PATCH,
MaterializeViewWorkflow,
MaterializeViewWorkflowInputs,
+ _StagedAuditVerdict,
)
from products.customer_analytics.backend.facade.temporal_contracts import StageAccountPropertySyncInput
@@ -176,7 +178,9 @@ class TestQualityGateBranching:
None, # quality_block_materialization
]
- result, execute_activity = await self._run(activity_results, {"checks_failed_blocking": 2})
+ result, execute_activity = await self._run(
+ activity_results, {"suite_run_id": "suite-1", "checks_failed_blocking": 2}
+ )
assert result.quality_blocking_failures == 2
assert result.quality_audited is True
@@ -184,6 +188,8 @@ class TestQualityGateBranching:
assert started[-2:] == ["stage_queryable_files_activity", "quality_block_materialization_activity"]
assert "publish_queryable_table_activity" not in started
assert "succeed_materialization_activity" not in started
+ block_inputs = execute_activity.await_args_list[-1].args[1]
+ assert block_inputs.suite_run_id == "suite-1"
assert execute_activity.await_args_list[0].args[1] == ManagedWarehouseShadowEligibilityInputs(
team_id=7,
dag_id="dag-1",
@@ -194,6 +200,24 @@ class TestQualityGateBranching:
== "check_managed_warehouse_shadow_eligibility_activity"
)
+ async def test_legacy_history_passes_no_suite_run_id_to_the_quality_block_activity(self):
+ activity_results = [
+ False,
+ "job-1",
+ _materialize_result("gate"),
+ StageQueryableFilesResult(staged_folder_path="staged_1"),
+ None,
+ ]
+
+ _, execute_activity = await self._run(
+ activity_results,
+ {"suite_run_id": "suite-1", "checks_failed_blocking": 2},
+ patched=lambda change_id: change_id != QUALITY_BLOCK_SUITE_RUN_ID_PATCH,
+ )
+
+ block_inputs = execute_activity.await_args_list[-1].args[1]
+ assert block_inputs.suite_run_id is None
+
async def test_account_staging_starts_an_isolated_child_workflow(self):
materialize_result = dataclasses.replace(
_materialize_result("skip"),
@@ -416,7 +440,7 @@ def _cancelled_child_error() -> ChildWorkflowError:
class TestStagedAudit:
- async def _staged_verdict(self, workflow: MaterializeViewWorkflow) -> int | None:
+ async def _staged_verdict(self, workflow: MaterializeViewWorkflow) -> _StagedAuditVerdict | None:
return await workflow._staged_audit_verdict(_inputs(), "job-1", _materialize_result("gate"), "staged_1")
async def test_reads_the_blocking_count_from_the_suite_result(self):
@@ -424,12 +448,22 @@ class TestStagedAudit:
with patch.object(temporalio.workflow, "execute_child_workflow", new=child):
verdict = await self._staged_verdict(MaterializeViewWorkflow())
- assert verdict == 3
+ assert verdict is not None
+ assert verdict.suite_run_id == "s-1"
+ assert verdict.blocking_failures == 3
assert child.await_args is not None
payload = child.await_args.args[1]
assert payload["saved_query_ids"] == ["sq-1"]
assert payload["staged_queryable_folder"] == "staged_1"
+ async def test_a_zero_failure_audit_has_a_verdict(self):
+ child = AsyncMock(return_value={"suite_run_id": "s-1", "checks_failed_blocking": 0})
+ with patch.object(temporalio.workflow, "execute_child_workflow", new=child):
+ verdict = await self._staged_verdict(MaterializeViewWorkflow())
+
+ assert verdict is not None
+ assert verdict.blocking_failures == 0
+
async def test_a_suite_that_errors_reaches_no_verdict(self):
with (
patch.object(
diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.py
index 064fbac4b8a3..cea234aa0eb8 100644
--- a/products/data_quality/backend/facade/api.py
+++ b/products/data_quality/backend/facade/api.py
@@ -26,6 +26,7 @@ from ..logic.config import get_gate_config, set_gate_materialization_on_checks
from ..logic.contracts import CompiledCheck, SubjectIdentity, SubjectRef
from ..logic.errors import CheckConfigError, CheckEditConflict, SubjectUnresolvableError
from ..logic.health import CheckStatusRow, roll_up_health
+from ..logic.materialization import materialization_failure_summary
from ..logic.navigation import SubjectKey, SubjectLocation, subject_locations
from ..logic.notifications import notify_materialization_blocked
from ..logic.output_schema import metric_output_schema
@@ -89,6 +90,7 @@ __all__ = [
"restrict_subject_types",
"sql_denial_context",
"live_subject_checks",
+ "materialization_failure_summary",
"caller_denial_context",
"can_be_object_denied",
"checks_for_subject",
diff --git a/products/data_quality/backend/logic/materialization.py b/products/data_quality/backend/logic/materialization.py
new file mode 100644
index 000000000000..de4af21aa5db
--- /dev/null
+++ b/products/data_quality/backend/logic/materialization.py
@@ -0,0 +1,116 @@
+from math import isfinite
+from uuid import UUID
+
+from ..facade.enums import CheckRunStatus, CheckSeverity, CheckType, SubjectType, SuiteRunStatus, SuiteRunTrigger
+from ..models import DataQualityCheckRun, DataQualitySuiteRun
+
+MAX_FAILURE_SUMMARIES = 3
+
+
+def materialization_failure_summary(
+ team_id: int,
+ *,
+ suite_run_id: str,
+ data_modeling_job_id: str,
+ saved_query_id: str,
+ blocking_failures: int,
+) -> str | None:
+ if not isinstance(blocking_failures, int) or isinstance(blocking_failures, bool) or blocking_failures < 1:
+ return None
+
+ suite_id = _parse_uuid(suite_run_id)
+ job_id = _parse_uuid(data_modeling_job_id)
+ subject_id = _parse_uuid(saved_query_id)
+ if suite_id is None or job_id is None or subject_id is None:
+ return None
+
+ suite_run = (
+ DataQualitySuiteRun.objects.for_team(team_id)
+ .filter(
+ id=suite_id,
+ trigger=SuiteRunTrigger.MATERIALIZATION,
+ status=SuiteRunStatus.COMPLETED,
+ data_modeling_job_id=job_id,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=subject_id,
+ )
+ .only("id")
+ .first()
+ )
+ if suite_run is None:
+ return None
+
+ snapshots = (
+ DataQualityCheckRun.objects.for_team(team_id)
+ .filter(
+ suite_run_id=suite_run.id,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=subject_id,
+ status=CheckRunStatus.FAILED,
+ check_severity=CheckSeverity.ERROR,
+ )
+ .order_by("created_at", "id")
+ )
+ if snapshots.count() != blocking_failures:
+ return None
+
+ details = [
+ _failure_detail(snapshot.check_type, snapshot.check_config, snapshot.observed_value)
+ for snapshot in snapshots[:MAX_FAILURE_SUMMARIES]
+ ]
+ if blocking_failures > MAX_FAILURE_SUMMARIES:
+ details.append("additional checks also failed")
+ return "; ".join(details)
+
+
+def _parse_uuid(value: str) -> UUID | None:
+ try:
+ return UUID(value)
+ except (AttributeError, TypeError, ValueError):
+ return None
+
+
+def _failure_detail(check_type: str, config: object, observed_value: object) -> str:
+ if check_type == CheckType.ROW_COUNT:
+ return _row_count_detail(config, observed_value)
+
+ fixed_reasons: dict[str, str] = {
+ CheckType.UNIQUE: "the uniqueness check found duplicate values",
+ CheckType.NOT_NULL: "the not-null check found null values",
+ CheckType.ACCEPTED_VALUES: "the accepted-values check found values outside its allowed set",
+ CheckType.RELATIONSHIPS: "a data quality check failed",
+ CheckType.FRESHNESS: "the latest timestamp is missing or too old",
+ CheckType.CUSTOM_SQL: "a data quality check failed",
+ }
+ return fixed_reasons.get(check_type, "a data quality check failed")
+
+
+def _row_count_detail(config: object, observed_value: object) -> str:
+ if not isinstance(config, dict):
+ return "a data quality check failed"
+
+ observed = _whole_number(observed_value)
+ minimum = _whole_number(config.get("min"))
+ maximum = _whole_number(config.get("max"))
+ if (
+ observed is None
+ or (minimum is None and maximum is None)
+ or (minimum is not None and maximum is not None and minimum > maximum)
+ ):
+ return "a data quality check failed"
+
+ if minimum is not None and observed < minimum:
+ return "the row count is below its minimum"
+ if maximum is not None and observed > maximum:
+ return "the row count is above its maximum"
+ return "a data quality check failed"
+
+
+def _whole_number(value: object) -> int | None:
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ return value if value >= 0 else None
+ if isinstance(value, float) and isfinite(value) and value.is_integer() and value >= 0:
+ return int(value)
+ return None
diff --git a/products/data_quality/backend/tests/test_materialization.py b/products/data_quality/backend/tests/test_materialization.py
new file mode 100644
index 000000000000..5cc55d5022cc
--- /dev/null
+++ b/products/data_quality/backend/tests/test_materialization.py
@@ -0,0 +1,195 @@
+from uuid import uuid4
+
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.data_quality.backend.facade import api
+from products.data_quality.backend.facade.enums import (
+ CheckRunStatus,
+ CheckSeverity,
+ CheckType,
+ SubjectType,
+ SuiteRunStatus,
+ SuiteRunTrigger,
+)
+from products.data_quality.backend.models import DataQualityCheckRun, DataQualitySuiteRun
+
+
+class TestMaterializationFailureSummary(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.job_id = uuid4()
+ self.subject_id = uuid4()
+
+ def _suite(self, **overrides: object) -> DataQualitySuiteRun:
+ defaults: dict[str, object] = {
+ "team": self.team,
+ "trigger": SuiteRunTrigger.MATERIALIZATION,
+ "status": SuiteRunStatus.COMPLETED,
+ "data_modeling_job_id": self.job_id,
+ "subject_type": SubjectType.VIEW,
+ "subject_uuid": self.subject_id,
+ }
+ return DataQualitySuiteRun.objects.for_team(self.team.id).create(**(defaults | overrides))
+
+ def _run(
+ self,
+ suite_run: DataQualitySuiteRun,
+ *,
+ check_type: CheckType | str = CheckType.NOT_NULL,
+ config: dict[str, object] | None = None,
+ observed_value: float | None = None,
+ **overrides: object,
+ ) -> DataQualityCheckRun:
+ defaults: dict[str, object] = {
+ "team": self.team,
+ "suite_run": suite_run,
+ "subject_type": SubjectType.VIEW,
+ "subject_uuid": self.subject_id,
+ "subject_name": "subject",
+ "check_type": check_type,
+ "check_fingerprint": uuid4().hex,
+ "check_config": {} if config is None else config,
+ "check_severity": CheckSeverity.ERROR,
+ "status": CheckRunStatus.FAILED,
+ "observed_value": observed_value,
+ }
+ return DataQualityCheckRun.objects.for_team(self.team.id).create(**(defaults | overrides))
+
+ def _summary(self, suite_run: DataQualitySuiteRun, blocking_failures: int = 1) -> str | None:
+ return api.materialization_failure_summary(
+ self.team.id,
+ suite_run_id=str(suite_run.id),
+ data_modeling_job_id=str(self.job_id),
+ saved_query_id=str(self.subject_id),
+ blocking_failures=blocking_failures,
+ )
+
+ @parameterized.expand(
+ [
+ ("below_minimum", {"min": 1_000}, 999, "the row count is below its minimum"),
+ ("above_maximum", {"max": 1_000}, 1_001, "the row count is above its maximum"),
+ ("below_bounded_range", {"min": 1_000, "max": 2_000}, 999, "the row count is below its minimum"),
+ ("above_bounded_range", {"min": 1_000, "max": 2_000}, 2_001, "the row count is above its maximum"),
+ ]
+ )
+ def test_uses_safe_row_count_failure_reason(
+ self, _name: str, config: dict[str, object], observed: int, expected: str
+ ) -> None:
+ suite_run = self._suite()
+ self._run(suite_run, check_type=CheckType.ROW_COUNT, config=config, observed_value=observed)
+
+ summary = self._summary(suite_run)
+ assert summary == expected
+ assert str(observed) not in summary
+ assert all(str(bound) not in summary for bound in config.values())
+
+ @parameterized.expand(
+ [
+ ("unique", CheckType.UNIQUE, "the uniqueness check found duplicate values"),
+ ("not_null", CheckType.NOT_NULL, "the not-null check found null values"),
+ (
+ "accepted_values",
+ CheckType.ACCEPTED_VALUES,
+ "the accepted-values check found values outside its allowed set",
+ ),
+ ("relationships", CheckType.RELATIONSHIPS, "a data quality check failed"),
+ ("freshness", CheckType.FRESHNESS, "the latest timestamp is missing or too old"),
+ ("custom_sql", CheckType.CUSTOM_SQL, "a data quality check failed"),
+ ("unknown", "future_type", "a data quality check failed"),
+ ]
+ )
+ def test_uses_fixed_reasons_for_non_row_count_checks(
+ self, _name: str, check_type: CheckType | str, expected: str
+ ) -> None:
+ suite_run = self._suite()
+ self._run(suite_run, check_type=check_type, config={"value": "not displayed"}, observed_value=123)
+
+ summary = self._summary(suite_run)
+ assert summary == expected
+ assert "123" not in summary
+ assert "not displayed" not in summary
+
+ def test_returns_none_when_the_blocking_count_does_not_match(self) -> None:
+ suite_run = self._suite()
+ self._run(suite_run)
+
+ assert self._summary(suite_run, blocking_failures=2) is None
+
+ def test_limits_failure_summaries(self) -> None:
+ suite_run = self._suite()
+ for _ in range(4):
+ self._run(suite_run, check_type=CheckType.UNIQUE)
+
+ assert self._summary(suite_run, blocking_failures=4) == (
+ "the uniqueness check found duplicate values; the uniqueness check found duplicate values; "
+ "the uniqueness check found duplicate values; additional checks also failed"
+ )
+
+ def test_filters_to_the_completed_materialization_suite_and_snapshot_failures(self) -> None:
+ suite_run = self._suite()
+ check_run = self._run(suite_run)
+ assert self._summary(suite_run) == "the not-null check found null values"
+ assert (
+ api.materialization_failure_summary(
+ self.team.id,
+ suite_run_id=str(suite_run.id),
+ data_modeling_job_id=str(uuid4()),
+ saved_query_id=str(self.subject_id),
+ blocking_failures=1,
+ )
+ is None
+ )
+ assert (
+ api.materialization_failure_summary(
+ self.team.id,
+ suite_run_id=str(suite_run.id),
+ data_modeling_job_id=str(self.job_id),
+ saved_query_id=str(uuid4()),
+ blocking_failures=1,
+ )
+ is None
+ )
+ other_team = Team.objects.create(organization=self.organization)
+ assert (
+ api.materialization_failure_summary(
+ other_team.id,
+ suite_run_id=str(suite_run.id),
+ data_modeling_job_id=str(self.job_id),
+ saved_query_id=str(self.subject_id),
+ blocking_failures=1,
+ )
+ is None
+ )
+
+ DataQualitySuiteRun.objects.for_team(self.team.id).filter(id=suite_run.id).update(
+ trigger=SuiteRunTrigger.MANUAL
+ )
+ assert self._summary(suite_run) is None
+ DataQualitySuiteRun.objects.for_team(self.team.id).filter(id=suite_run.id).update(
+ trigger=SuiteRunTrigger.MATERIALIZATION,
+ status=SuiteRunStatus.RUNNING,
+ )
+ assert self._summary(suite_run) is None
+ DataQualitySuiteRun.objects.for_team(self.team.id).filter(id=suite_run.id).update(
+ status=SuiteRunStatus.COMPLETED
+ )
+
+ DataQualityCheckRun.objects.for_team(self.team.id).filter(id=check_run.id).update(
+ check_severity=CheckSeverity.WARN
+ )
+ assert self._summary(suite_run) is None
+ DataQualityCheckRun.objects.for_team(self.team.id).filter(id=check_run.id).update(
+ check_severity=CheckSeverity.ERROR,
+ status=CheckRunStatus.PASSED,
+ )
+ assert self._summary(suite_run) is None
+
+ def test_uses_only_complete_row_count_snapshots(self) -> None:
+ suite_run = self._suite()
+ self._run(suite_run, check_type=CheckType.ROW_COUNT, config={"min": 1}, observed_value=None)
+
+ assert self._summary(suite_run) == "a data quality check failed"