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): finish the suite before notifying (#101252)

Thiago Salvatore421c5a14655b
diff --git a/products/data_quality/backend/logic/notifications.py b/products/data_quality/backend/logic/notifications.py
index 4f5d3856c7af..5b051ce5a906 100644
--- a/products/data_quality/backend/logic/notifications.py
+++ b/products/data_quality/backend/logic/notifications.py
@@ -71,6 +71,7 @@ class _WarehouseSubjectResolver(RecipientsResolver):
referenced_names: list[str] | None = None,
executed_references: Sequence[dict[str, str]] = (),
references_unknown: bool = False,
+ access_cache: dict[int, UserAccessControl] | None = None,
) -> None:
self._team = team
self._subject_type = subject_type
@@ -81,7 +82,7 @@ class _WarehouseSubjectResolver(RecipientsResolver):
# One access-control object per member, reused across both gates below (and the warehouse
# database build the referenced-subject gate runs) so a single failing check doesn't rebuild
# it -- and its membership, role, and access-control lookups -- once per pass.
- self._access: dict[int, UserAccessControl] = {}
+ self._access: dict[int, UserAccessControl] = access_cache if access_cache is not None else {}
self._gates: dict[DenialContextKey, ReferenceGate] = {}
self._subject_metadata: SubjectMetadata | None = None
@@ -158,19 +159,24 @@ class _WarehouseSubjectResolver(RecipientsResolver):
def notify_check_started_failing(
- check: DataQualityCheck, failed_row_count: int | None, *, executed_references: Sequence[dict[str, str]] | None = ()
-) -> None:
- """Best-effort: a notification failure must never take down the run that produced it."""
+ check: DataQualityCheck,
+ failed_row_count: int | None,
+ *,
+ executed_references: Sequence[dict[str, str]] | None = (),
+ idempotency_key: str | None = None,
+ access_cache: dict[int, UserAccessControl] | None = None,
+) -> int:
+ """How many members were told. Best-effort: a failure here must never fail the run behind it."""
try:
if not is_data_quality_checks_enabled_for_team_id(check.team_id) or check.subject_uuid is None:
- return
+ return 0
team = Team.objects.get(id=check.team_id)
subject = resolve_subject(team.id, check.subject_type, check.subject_uuid)
if not subject.exists:
- return
+ return 0
is_metric = check.subject_type == SubjectType.METRIC
subject_name = subject.name if is_metric else check.subject_name
- create_notification(
+ event = create_notification(
NotificationData(
team_id=check.team_id,
notification_type=NotificationType.DATA_QUALITY_CHECK_FAILURE,
@@ -187,6 +193,7 @@ def notify_check_started_failing(
source_url=f"/project/{team.id}/data-catalog/metrics/{quote(subject_name, safe='')}?tab=tests"
if is_metric
else "",
+ idempotency_key=idempotency_key,
resolver=_WarehouseSubjectResolver(
team,
check.subject_type,
@@ -194,11 +201,14 @@ def notify_check_started_failing(
referenced_names=referenced_subject_names(team.id, check.check_type, check.config, subject=subject),
executed_references=executed_references or (),
references_unknown=executed_references is None,
+ access_cache=access_cache,
),
)
)
+ return len(event.resolved_user_ids) if event is not None else 0
except Exception:
LOGGER.exception("Could not send a data quality failure notification", check_id=str(check.id))
+ return 0
def notify_materialization_blocked(
diff --git a/products/data_quality/backend/logic/runner.py b/products/data_quality/backend/logic/runner.py
index 6960ea825f96..52cfb397a45b 100644
--- a/products/data_quality/backend/logic/runner.py
+++ b/products/data_quality/backend/logic/runner.py
@@ -26,11 +26,10 @@ from posthog.models.scoping import team_scope
from posthog.models.team import Team
from posthog.models.user import User
-from ..facade.enums import CheckRunStatus, CheckSeverity, SubjectStatus, SubjectType, SuiteRunTrigger
+from ..facade.enums import CheckRunStatus, SubjectStatus, SubjectType, SuiteRunTrigger
from ..models import DataQualityCheck, DataQualitySuiteRun
from .compiler import compile_check, related_subject_ref
from .contracts import CompiledCheck, Evaluation, SubjectRef
-from .notifications import notify_check_started_failing
from .run_records import record_check_run
from .staged_audit import StagedSubjectOverride, build_staged_database
from .subject_access import check_type_reads_beyond_subject, pin_referenced_subjects
@@ -57,7 +56,6 @@ class CheckOutcome:
observed_value: float | None = None
compiled_query: str = ""
error: str = ""
- became_failing: bool = False
referenced_subjects: list[dict[str, str]] | None | _ReferenceState = _ReferenceState.NOT_SUPPLIED
@@ -84,24 +82,11 @@ def run_check(
outcome = CheckOutcome(status=CheckRunStatus.ERRORED, error=str(err))
duration_ms = int((time.monotonic() - monotonic_start) * 1000)
+ finished_at = datetime.now(UTC)
with team_scope(team.id):
- _record_run(check, suite_run, outcome, started_at, duration_ms)
- became_failing = (
- outcome.status is CheckRunStatus.FAILED
- and check.severity == CheckSeverity.ERROR
- and _claim_failing_transition(check)
- )
- _update_check(check, outcome)
-
- if became_failing:
- notify_check_started_failing(
- check,
- outcome.failed_row_count,
- executed_references=None
- if outcome.referenced_subjects is _ReferenceState.NOT_SUPPLIED
- else outcome.referenced_subjects,
- )
- return replace(outcome, became_failing=became_failing)
+ _record_run(check, suite_run, outcome, started_at, finished_at, duration_ms)
+ _update_check(check, outcome, finished_at)
+ return outcome
def record_unrunnable_check(
@@ -112,29 +97,13 @@ def record_unrunnable_check(
) -> CheckOutcome:
"""A check with no run row reads, in the health state and the API, exactly like one that passed."""
outcome = CheckOutcome(status=CheckRunStatus.ERRORED, error=reason)
+ finished_at = datetime.now(UTC)
with team_scope(team.id):
- _record_run(check, suite_run, outcome, datetime.now(UTC), duration_ms=0)
- _update_check(check, outcome)
+ _record_run(check, suite_run, outcome, finished_at, finished_at, duration_ms=0)
+ _update_check(check, outcome, finished_at)
return outcome
-def _claim_failing_transition(check: DataQualityCheck) -> bool:
- """Whether this run is the one that moved the check into failing.
-
- Runs of the same check can overlap -- a manual run alongside the scheduled one -- and comparing
- against a status read in Python lets both of them see the same passing value and notify. The
- conditional update lets exactly one flip the row, so the pass-to-fail edge notifies once. Must
- run before ``_update_check`` writes the new status, or there is nothing left to claim.
- """
- return (
- DataQualityCheck.objects.for_team(check.team_id)
- .filter(id=check.id)
- .exclude(last_status=CheckRunStatus.FAILED)
- .update(last_status=CheckRunStatus.FAILED)
- == 1
- )
-
-
@dataclass(frozen=True)
class _Authorization:
"""How one run's query executes against warehouse access control."""
@@ -352,6 +321,7 @@ def _record_run(
suite_run: DataQualitySuiteRun,
outcome: CheckOutcome,
started_at: datetime,
+ finished_at: datetime,
duration_ms: int,
) -> None:
if check.subject_uuid is None:
@@ -385,17 +355,17 @@ def _record_run(
error=outcome.error,
duration_ms=duration_ms,
started_at=started_at,
- finished_at=datetime.now(UTC),
+ finished_at=finished_at,
)
-def _update_check(check: DataQualityCheck, outcome: CheckOutcome) -> None:
- ran_at = datetime.now(UTC)
+def _update_check(check: DataQualityCheck, outcome: CheckOutcome, finished_at: datetime) -> None:
+ """Stamps the check with the instant its run row carries, so failing_since matches the opening run's finished_at."""
check.last_status = outcome.status
- check.last_run_at = ran_at
+ check.last_run_at = finished_at
updated = ["last_status", "last_run_at", "subject_name", "subject_status", "updated_at"]
if outcome.status is CheckRunStatus.PASSED:
- check.last_succeeded_at = ran_at
+ check.last_succeeded_at = finished_at
# Written only by the run that earned it. A failing run holds whatever this row said when its
# batch loaded it, so listing the column unconditionally would let it overwrite a success a
# concurrent run committed in between.
@@ -414,7 +384,7 @@ def _update_check(check: DataQualityCheck, outcome: CheckOutcome) -> None:
with transaction.atomic():
check.save(update_fields=updated)
if outcome.status in FAILING_STATUSES:
- _claim_failing_streak(check, ran_at)
+ _claim_failing_streak(check, finished_at)
def _claim_failing_streak(check: DataQualityCheck, failed_at: datetime) -> None:
diff --git a/products/data_quality/backend/temporal/__init__.py b/products/data_quality/backend/temporal/__init__.py
index 5d38deb0664c..2adfbe1fdc92 100644
--- a/products/data_quality/backend/temporal/__init__.py
+++ b/products/data_quality/backend/temporal/__init__.py
@@ -12,6 +12,7 @@ from .activities.finalize_check_suite import (
mark_check_suite_failed_activity,
)
from .activities.materialization_gate import materialization_gate_activity
+from .activities.notify_failing_checks import notify_failing_checks_activity
from .activities.prepare_check_suite import prepare_check_suite_activity
from .activities.reconcile_schedules import reconcile_metric_schedules_activity
from .activities.run_check_batch import run_check_batch_activity
@@ -32,6 +33,7 @@ ACTIVITIES: list[Callable[..., Any]] = [
finalize_check_suite_activity,
mark_check_suite_empty_activity,
mark_check_suite_failed_activity,
+ notify_failing_checks_activity,
cleanup_check_runs_activity,
reconcile_metric_schedules_activity,
]
diff --git a/products/data_quality/backend/temporal/activities/notify_failing_checks.py b/products/data_quality/backend/temporal/activities/notify_failing_checks.py
new file mode 100644
index 000000000000..ca199e7e5692
--- /dev/null
+++ b/products/data_quality/backend/temporal/activities/notify_failing_checks.py
@@ -0,0 +1,94 @@
+import time
+from datetime import datetime
+
+from django.db.models import F
+
+from temporalio import activity
+
+from posthog.sync import database_sync_to_async_pool
+from posthog.temporal.common.heartbeat import Heartbeater
+from posthog.temporal.common.logger import get_logger
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+from ...facade.enums import CheckRunStatus, CheckSeverity
+from ...logic.notifications import notify_check_started_failing
+from ...logic.runner import FAILING_STATUSES
+from ...models import DataQualityCheckRun, DataQualitySuiteRun
+from ..contracts import NotifyFailingChecksInputs
+
+LOGGER = get_logger(__name__)
+
+
+async def notify_failing_checks_activity(inputs: NotifyFailingChecksInputs) -> None:
+ async with Heartbeater():
+ await database_sync_to_async_pool(_notify_failing_checks)(inputs)
+
+
+def _notify_failing_checks(inputs: NotifyFailingChecksInputs) -> None:
+ """Tell the team about every check this suite moved into failing.
+
+ Derived from the streak each check persisted, never from what a batch reported, so a batch that
+ claimed the streak and then timed out still notifies on its retry.
+ """
+ suite_run = DataQualitySuiteRun.objects.for_team(inputs.team_id).get(id=inputs.suite_run_id)
+ runs = _runs_that_started_failing(inputs.team_id, suite_run)
+ access_cache: dict[int, UserAccessControl] = {}
+ notified = 0
+
+ for run in runs:
+ check = run.quality_check
+ if check is None or check.failing_since is None:
+ continue
+ started = time.monotonic()
+ recipients = notify_check_started_failing(
+ check,
+ run.failed_row_count,
+ executed_references=run.referenced_subjects,
+ idempotency_key=failing_streak_key(str(check.id), check.failing_since),
+ access_cache=access_cache,
+ )
+ notified += 1
+ LOGGER.info(
+ "Notified a newly failing check",
+ suite_run_id=inputs.suite_run_id,
+ check_id=str(check.id),
+ recipients=recipients,
+ elapsed_ms=int((time.monotonic() - started) * 1000),
+ )
+
+ LOGGER.info(
+ "Notified the checks a suite moved into failing",
+ suite_run_id=inputs.suite_run_id,
+ checks=notified,
+ members=len(access_cache),
+ )
+
+
+def failing_streak_key(check_id: str, failing_since: datetime) -> str:
+ """The idempotency key for one streak, so overlapping suites collapse to a single notice."""
+ return f"check-failing-{check_id}-{failing_since.isoformat()}"
+
+
+def _runs_that_started_failing(team_id: int, suite_run: DataQualitySuiteRun) -> list[DataQualityCheckRun]:
+ """The suite's failed runs that are themselves the run the check's current streak started from.
+
+ The runner stamps one instant on both rows, so a run opened the streak only when its
+ ``finished_at`` is the check's ``failing_since``. A check that recovered and failed again is on
+ a streak another run opened, and that run's notice carries its own row count and references.
+
+ Severity comes from the run row, not the definition, so an edit between the batch and this
+ activity cannot change what the suite already reported, or make one retry differ from the next.
+ """
+ return list(
+ DataQualityCheckRun.objects.for_team(team_id)
+ .filter(
+ suite_run_id=suite_run.id,
+ status=CheckRunStatus.FAILED,
+ check_severity=CheckSeverity.ERROR,
+ quality_check__last_status__in=FAILING_STATUSES,
+ quality_check__failing_since=F("finished_at"),
+ )
+ .select_related("quality_check")
+ )
diff --git a/products/data_quality/backend/temporal/activities/run_check_batch.py b/products/data_quality/backend/temporal/activities/run_check_batch.py
index ccafd966abd4..054fd5c35835 100644
--- a/products/data_quality/backend/temporal/activities/run_check_batch.py
+++ b/products/data_quality/backend/temporal/activities/run_check_batch.py
@@ -61,7 +61,6 @@ def _run_batch(inputs: RunCheckBatchInputs) -> BatchOutcome:
counts: Counter[str] = Counter()
failed_blocking = 0
- newly_failing: list[str] = []
for check in checks:
# run_check records a compile or query failure as an errored run rather than raising: one
# broken check must not fail the activity and take its whole batch down with it.
@@ -69,8 +68,6 @@ def _run_batch(inputs: RunCheckBatchInputs) -> BatchOutcome:
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(
@@ -79,5 +76,4 @@ def _run_batch(inputs: RunCheckBatchInputs) -> BatchOutcome:
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.py
index 7d84773491f0..0de146e3842a 100644
--- a/products/data_quality/backend/temporal/contracts.py
+++ b/products/data_quality/backend/temporal/contracts.py
@@ -4,8 +4,6 @@ Flat, JSON-friendly dataclasses: workflow inputs also arrive from the management
single JSON object, so nested dataclasses would not survive ``parse_inputs``.
"""
-import dataclasses
-
from posthog.dataclasses import frozen
from ..facade.contracts import RunCheckSuiteInputs as RunCheckSuiteInputs
@@ -40,7 +38,6 @@ class BatchOutcome:
errored: int = 0
skipped: int = 0
failed_blocking: int = 0
- newly_failing_check_ids: list[str] = dataclasses.field(default_factory=list)
@frozen
@@ -50,6 +47,12 @@ class FinalizeCheckSuiteInputs:
outcomes: list[BatchOutcome]
+@frozen
+class NotifyFailingChecksInputs:
+ team_id: int
+ suite_run_id: str
+
+
@frozen
class MarkSuiteFailedInputs:
team_id: int
diff --git a/products/data_quality/backend/temporal/workflows/run_check_suite.py b/products/data_quality/backend/temporal/workflows/run_check_suite.py
index d3eb3599cdd8..f7dd5698e333 100644
--- a/products/data_quality/backend/temporal/workflows/run_check_suite.py
+++ b/products/data_quality/backend/temporal/workflows/run_check_suite.py
@@ -11,6 +11,7 @@ from ..activities.finalize_check_suite import (
mark_check_suite_empty_activity,
mark_check_suite_failed_activity,
)
+from ..activities.notify_failing_checks import notify_failing_checks_activity
from ..activities.prepare_check_suite import prepare_check_suite_activity
from ..activities.run_check_batch import run_check_batch_activity
from ..contracts import (
@@ -18,6 +19,7 @@ from ..contracts import (
CheckSuiteResult,
FinalizeCheckSuiteInputs,
MarkSuiteFailedInputs,
+ NotifyFailingChecksInputs,
PreparedSuite,
RunCheckBatchInputs,
RunCheckSuiteInputs,
@@ -57,7 +59,7 @@ class RunCheckSuiteWorkflow(PostHogWorkflow):
)
outcomes = await self._run_batches(inputs, prepared)
- return await workflow.execute_activity(
+ result: CheckSuiteResult = 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),
@@ -73,6 +75,24 @@ class RunCheckSuiteWorkflow(PostHogWorkflow):
)
raise
+ await self._notify_failing_checks(inputs.team_id, result)
+ return result
+
+ async def _notify_failing_checks(self, team_id: int, result: CheckSuiteResult) -> None:
+ """Runs after the suite is finished, so a slow or broken fan-out cannot hold it in running."""
+ if result.checks_failed <= 0:
+ return
+ try:
+ await workflow.execute_activity(
+ notify_failing_checks_activity,
+ NotifyFailingChecksInputs(team_id=team_id, suite_run_id=result.suite_run_id),
+ start_to_close_timeout=dt.timedelta(minutes=10),
+ heartbeat_timeout=dt.timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ except Exception:
+ workflow.logger.exception("Could not notify the checks a suite moved into failing")
+
async def _run_batches(self, inputs: RunCheckSuiteInputs, prepared: PreparedSuite) -> list[BatchOutcome]:
semaphore = asyncio.Semaphore(MAX_CONCURRENT_BATCHES)
staged_saved_query_id = (
diff --git a/products/data_quality/backend/tests/test_notifications.py b/products/data_quality/backend/tests/test_notifications.py
index 3ced6f06ac31..5ae934cda27b 100644
--- a/products/data_quality/backend/tests/test_notifications.py
+++ b/products/data_quality/backend/tests/test_notifications.py
@@ -1,4 +1,5 @@
from contextlib import nullcontext
+from datetime import timedelta
from uuid import uuid4
from posthog.test.base import BaseTest
@@ -34,6 +35,8 @@ from products.data_quality.backend.logic.notifications import (
from products.data_quality.backend.logic.runner import run_check
from products.data_quality.backend.logic.subject_access import referenced_subject_names
from products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun
+from products.data_quality.backend.temporal.activities.notify_failing_checks import _notify_failing_checks
+from products.data_quality.backend.temporal.contracts import NotifyFailingChecksInputs
from products.notifications.backend.facade.enums import TargetType
from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource
@@ -75,6 +78,10 @@ class TestDataQualityNotifications(BaseTest):
}
return DataQualityCheck.objects.for_team(self.team.id).create(**{**defaults, **kwargs})
+ def _run_and_notify(self, check: DataQualityCheck) -> None:
+ run_check(check, self.suite_run, self.team)
+ _notify_failing_checks(NotifyFailingChecksInputs(team_id=self.team.id, suite_run_id=str(self.suite_run.id)))
+
def _resolver_for(self, check: DataQualityCheck) -> _WarehouseSubjectResolver:
return _WarehouseSubjectResolver(
self.team,
@@ -163,6 +170,9 @@ class TestDataQualityNotifications(BaseTest):
with patch(RUNNER_QUERY, side_effect=change_metric), pinning:
outcome = run_check(check, self.suite_run, self.team)
assert outcome.status == CheckRunStatus.FAILED
+ _notify_failing_checks(
+ NotifyFailingChecksInputs(team_id=self.team.id, suite_run_id=str(self.suite_run.id))
+ )
else:
notify_check_started_failing(check, 3)
assert notifications.call_count == 1
@@ -209,22 +219,32 @@ class TestDataQualityNotifications(BaseTest):
@parameterized.expand(
[
- ("first_failure", "", CheckSeverity.ERROR, 3, 1),
- ("still_failing", CheckRunStatus.FAILED, CheckSeverity.ERROR, 3, 0),
- ("recovered_then_failed_again", CheckRunStatus.PASSED, CheckSeverity.ERROR, 3, 1),
- ("warn_severity_failure", "", CheckSeverity.WARN, 3, 0),
- ("passing", "", CheckSeverity.ERROR, 0, 0),
- ("recovery", CheckRunStatus.FAILED, CheckSeverity.ERROR, 0, 0),
+ ("first_failure", "", None, CheckSeverity.ERROR, 3, 1),
+ ("still_failing", CheckRunStatus.FAILED, "before_the_suite", CheckSeverity.ERROR, 3, 0),
+ ("recovered_then_failed_again", CheckRunStatus.PASSED, None, CheckSeverity.ERROR, 3, 1),
+ ("warn_severity_failure", "", None, CheckSeverity.WARN, 3, 0),
+ ("passing", "", None, CheckSeverity.ERROR, 0, 0),
+ ("recovery", CheckRunStatus.FAILED, "before_the_suite", CheckSeverity.ERROR, 0, 0),
]
)
def test_only_a_pass_to_fail_edge_on_an_error_check_notifies(
- self, _name, previous_status: str, severity: CheckSeverity, failure_count: int, expected_calls: int
+ self,
+ _name,
+ previous_status: str,
+ streak_start: str | None,
+ severity: CheckSeverity,
+ failure_count: int,
+ expected_calls: int,
) -> None:
- check = self._check(last_status=previous_status, severity=severity)
+ check = self._check(
+ last_status=previous_status,
+ severity=severity,
+ failing_since=self.suite_run.created_at - timedelta(minutes=5) if streak_start else None,
+ )
with patch(CREATE_NOTIFICATION) as create_notification:
with patch(RUNNER_QUERY, return_value=_Response(failure_count)):
- run_check(check, self.suite_run, self.team)
+ self._run_and_notify(check)
assert create_notification.call_count == expected_calls
@@ -233,7 +253,7 @@ class TestDataQualityNotifications(BaseTest):
with patch(CREATE_NOTIFICATION) as create_notification:
with patch(RUNNER_QUERY, return_value=_Response(4)):
- run_check(check, self.suite_run, self.team)
+ self._run_and_notify(check)
payload = create_notification.call_args.args[0]
assert payload.title == "Data quality check failed on orders"
@@ -247,7 +267,7 @@ class TestDataQualityNotifications(BaseTest):
with patch(CREATE_NOTIFICATION) as create_notification:
with patch(RUNNER_QUERY, return_value=_Response(4)):
- run_check(check, self.suite_run, self.team)
+ self._run_and_notify(check)
assert create_notification.call_args.args[0].resource_type == "warehouse_objects"
diff --git a/products/data_quality/backend/tests/test_run_check_suite.py b/products/data_quality/backend/tests/test_run_check_suite.py
index d8db6f2449de..4cb6ae38a3ef 100644
--- a/products/data_quality/backend/tests/test_run_check_suite.py
+++ b/products/data_quality/backend/tests/test_run_check_suite.py
@@ -1,7 +1,9 @@
+from contextlib import nullcontext
+from datetime import timedelta
from uuid import uuid4
from posthog.test.base import BaseTest
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
from asgiref.sync import async_to_sync
from parameterized import parameterized
@@ -10,6 +12,7 @@ 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,
+ CheckSeverity,
CheckType,
SubjectType,
SuiteRunStatus,
@@ -17,12 +20,14 @@ from products.data_quality.backend.facade.enums import (
)
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.notify_failing_checks import _notify_failing_checks
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,
+ NotifyFailingChecksInputs,
PreparedSuite,
RunCheckBatchInputs,
RunCheckSuiteInputs,
@@ -34,6 +39,9 @@ ACTIVITY_INFO = "products.data_quality.backend.temporal.activities.prepare_check
PREPARE_FLAG = (
"products.data_quality.backend.temporal.activities.prepare_check_suite.get_data_quality_checks_flag_for_team_id"
)
+NOTIFY_ONE_CHECK = (
+ "products.data_quality.backend.temporal.activities.notify_failing_checks.notify_check_started_failing"
+)
class _Response:
@@ -200,7 +208,6 @@ class TestCheckSuiteActivities(BaseTest):
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
@@ -246,6 +253,117 @@ class TestCheckSuiteActivities(BaseTest):
assert run.status == CheckRunStatus.ERRORED
assert "staged files" in run.error
+ def _fail_checks(self, checks: list[DataQualityCheck]) -> str:
+ suite_run_id = self._prepare(created_by_id=self.user.id).suite_run_id
+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [4, 4])):
+ _run_batch(
+ RunCheckBatchInputs(
+ team_id=self.team.id,
+ suite_run_id=suite_run_id,
+ check_ids=[str(check.id) for check in checks],
+ )
+ )
+ return suite_run_id
+
+ def _notify(self, suite_run_id: str) -> MagicMock:
+ with patch(NOTIFY_ONE_CHECK, return_value=1) as notify:
+ _notify_failing_checks(NotifyFailingChecksInputs(team_id=self.team.id, suite_run_id=suite_run_id))
+ return notify
+
+ @parameterized.expand(
+ [
+ ("error_severity_first_failure", CheckSeverity.ERROR, None, "", True),
+ ("warn_severity", CheckSeverity.WARN, None, "", False),
+ ("a_streak_opened_before_this_run", CheckSeverity.ERROR, timedelta(minutes=-5), "", False),
+ ("a_streak_reopened_after_this_run", CheckSeverity.ERROR, timedelta(milliseconds=1), "", False),
+ ("an_overlapping_run_errored_after_this_one", CheckSeverity.ERROR, None, CheckRunStatus.ERRORED, True),
+ ("the_check_has_since_passed", CheckSeverity.ERROR, None, CheckRunStatus.PASSED, False),
+ ]
+ )
+ def test_only_the_checks_this_suite_moved_into_failing_are_notified(
+ self, _name: str, severity: CheckSeverity, streak_shift: timedelta | None, newest_status: str, expected: bool
+ ) -> None:
+ check = self._check(severity=severity)
+ suite_run_id = self._fail_checks([check])
+ if newest_status:
+ updates: dict = {"last_status": newest_status}
+ if newest_status == CheckRunStatus.PASSED:
+ updates["failing_since"] = None
+ DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id).update(**updates)
+ if streak_shift is not None:
+ run = DataQualityCheckRun.objects.for_team(self.team.id).get(suite_run_id=suite_run_id)
+ assert run.finished_at is not None
+ DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id).update(
+ failing_since=run.finished_at + streak_shift
+ )
+
+ notify = self._notify(suite_run_id)
+
+ assert notify.call_count == (1 if expected else 0)
+
+ @parameterized.expand(
+ [("lowered_to_warn", CheckSeverity.WARN, True), ("raised_to_error", CheckSeverity.ERROR, False)]
+ )
+ def test_a_severity_edit_after_the_batch_does_not_change_what_the_suite_reports(
+ self, _name: str, edited_to: CheckSeverity, expected: bool
+ ) -> None:
+ check = self._check(severity=CheckSeverity.ERROR if expected else CheckSeverity.WARN)
+ suite_run_id = self._fail_checks([check])
+ DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id).update(severity=edited_to)
+
+ notify = self._notify(suite_run_id)
+
+ assert notify.call_count == (1 if expected else 0)
+
+ def test_the_idempotency_key_names_the_check_and_the_streak_it_opened(self) -> None:
+ check = self._check()
+ suite_run_id = self._fail_checks([check])
+
+ notify = self._notify(suite_run_id)
+
+ check.refresh_from_db()
+ assert check.failing_since is not None
+ assert notify.call_args.kwargs["idempotency_key"] == (
+ f"check-failing-{check.id}-{check.failing_since.isoformat()}"
+ )
+
+ @parameterized.expand([("pinned", False), ("unpinnable", True)])
+ def test_the_references_the_run_pinned_are_handed_to_the_notice(self, _name: str, unpinnable: bool) -> None:
+ check = self._check(check_type=CheckType.CUSTOM_SQL, column_name="", config={"query": "SELECT 1 FROM orders"})
+ pinning = (
+ patch("products.data_quality.backend.logic.runner.pin_referenced_subjects", return_value=None)
+ if unpinnable
+ else nullcontext()
+ )
+ with pinning:
+ suite_run_id = self._fail_checks([check])
+
+ notify = self._notify(suite_run_id)
+
+ expected = None if unpinnable else [{"subject_type": SubjectType.VIEW, "subject_uuid": str(self.view.id)}]
+ assert notify.call_args.kwargs["executed_references"] == expected
+
+ def test_the_checks_of_one_activity_share_one_access_lookup_per_member(self) -> None:
+ first = self._check()
+ second = self._check(column_name="total")
+ suite_run_id = self._fail_checks([first, second])
+
+ notify = self._notify(suite_run_id)
+
+ caches = [call.kwargs["access_cache"] for call in notify.call_args_list]
+ assert len(caches) == 2
+ assert caches[0] is caches[1]
+
+ def test_a_check_hard_deleted_after_its_batch_leaves_the_others_notified(self) -> None:
+ deleted = self._check()
+ survivor = self._check(column_name="total")
+ suite_run_id = self._fail_checks([deleted, survivor])
+ DataQualityCheck.objects.for_team(self.team.id).filter(id=deleted.id).delete()
+
+ notify = self._notify(suite_run_id)
+
+ assert [call.args[0].id for call in notify.call_args_list] == [survivor.id]
+
def test_finalize_sums_batch_outcomes_into_the_report(self) -> None:
prepared = self._prepare()
@@ -284,7 +402,12 @@ class TestCheckSuiteActivities(BaseTest):
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):
+ # workflow.logger only resolves inside a real workflow event loop, and these drive the
+ # coroutine directly.
+ with (
+ patch.object(temporal_workflow, "execute_activity", new=execute_activity),
+ patch.object(temporal_workflow, "logger"),
+ ):
result = async_to_sync(RunCheckSuiteWorkflow().run)(
RunCheckSuiteInputs(team_id=self.team.id, trigger=SuiteRunTrigger.MANUAL)
)
@@ -301,9 +424,11 @@ class TestRunCheckSuiteWorkflow(BaseTest):
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)
+ completed = CheckSuiteResult(suite_run_id="s-1", status=SuiteRunStatus.COMPLETED, checks_failed=1)
- result, execute_activity = self._run(prepared, [BatchOutcome(passed=1), BatchOutcome(failed=1), completed])
+ result, execute_activity = self._run(
+ prepared, [BatchOutcome(passed=1), BatchOutcome(failed=1), completed, None]
+ )
assert result.status == SuiteRunStatus.COMPLETED
started = [call.args[0].__name__ for call in execute_activity.await_args_list]
@@ -312,9 +437,33 @@ class TestRunCheckSuiteWorkflow(BaseTest):
"run_check_batch_activity",
"run_check_batch_activity",
"finalize_check_suite_activity",
+ "notify_failing_checks_activity",
]
- finalize_inputs = execute_activity.await_args_list[-1].args[1]
+ finalize_inputs = execute_activity.await_args_list[-2].args[1]
assert [outcome.passed for outcome in finalize_inputs.outcomes] == [1, 0]
+ assert execute_activity.await_args_list[-1].args[1].suite_run_id == "s-1"
+
+ def test_a_suite_with_nothing_failing_does_not_notify(self) -> None:
+ prepared = PreparedSuite(suite_run_id="s-1", batches=[["a"]])
+ completed = CheckSuiteResult(suite_run_id="s-1", status=SuiteRunStatus.COMPLETED, checks_errored=1)
+
+ result, execute_activity = self._run(prepared, [BatchOutcome(errored=1), completed])
+
+ assert result.status == SuiteRunStatus.COMPLETED
+ started = [call.args[0].__name__ for call in execute_activity.await_args_list]
+ assert "notify_failing_checks_activity" not in started
+
+ def test_a_notify_failure_leaves_the_suite_completed(self) -> None:
+ prepared = PreparedSuite(suite_run_id="s-1", batches=[["a"]])
+ completed = CheckSuiteResult(suite_run_id="s-1", status=SuiteRunStatus.COMPLETED, checks_failed=1)
+
+ result, execute_activity = self._run(
+ prepared, [BatchOutcome(failed=1), completed, RuntimeError("the notifications backend is down")]
+ )
+
+ assert result.status == SuiteRunStatus.COMPLETED
+ started = [call.args[0].__name__ for call in execute_activity.await_args_list]
+ assert "mark_check_suite_failed_activity" not in started
def test_a_failed_batch_marks_the_prepared_suite_failed_and_reraises(self) -> None:
prepared = PreparedSuite(suite_run_id="s-1", batches=[["a"]])
diff --git a/products/data_quality/backend/tests/test_runner.py b/products/data_quality/backend/tests/test_runner.py
index 947cc6f36bb4..ca693432dd29 100644
--- a/products/data_quality/backend/tests/test_runner.py
+++ b/products/data_quality/backend/tests/test_runner.py
@@ -29,6 +29,7 @@ from products.data_quality.backend.models import DataQualityCheck, DataQualityCh
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
RUNNER_QUERY = "products.data_quality.backend.logic.runner.execute_hogql_query"
+CREATE_NOTIFICATION = "products.data_quality.backend.logic.notifications.create_notification"
class _Response:
@@ -497,33 +498,14 @@ class TestCheckRunner(BaseTest):
query.assert_not_called()
assert outcome.status == CheckRunStatus.ERRORED
- @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.FAILED
-
- def test_an_overlapping_run_does_not_claim_the_same_failing_transition(self) -> None:
- # Stands in for a manual run racing the scheduled one: this run still holds the passing
- # status it loaded, but the row already moved to failing, so it must not notify a second time.
+ def test_a_failing_run_records_the_outcome_without_notifying(self) -> None:
check = self._check(last_status=CheckRunStatus.PASSED, severity=CheckSeverity.ERROR)
- DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id).update(last_status=CheckRunStatus.FAILED)
- with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [3, 3])):
- outcome = run_check(check, self.suite_run, self.team)
+ with patch(CREATE_NOTIFICATION) as create_notification:
+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [3, 3])):
+ outcome = run_check(check, self.suite_run, self.team)
+ create_notification.assert_not_called()
assert outcome.status == CheckRunStatus.FAILED
- assert outcome.became_failing is False
+ check.refresh_from_db()
+ assert check.last_status == CheckRunStatus.FAILED