: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
fix(data-quality): count the failing duration from the failure (#93719)
Thiago Salvatoreb56f37c9927e
diff --git a/products/data_quality/backend/logic/runner.py b/products/data_quality/backend/logic/runner.pyindex f5bd70093a4e..366fe3728473 100644--- a/products/data_quality/backend/logic/runner.py+++ b/products/data_quality/backend/logic/runner.py@@ -12,6 +12,8 @@ from dataclasses import dataclass, replacefrom datetime import UTC, datetimefrom typing import TYPE_CHECKING, Any+from django.db import transaction+from posthog.hogql.context import HogQLContextfrom posthog.hogql.query import execute_hogql_query@@ -35,6 +37,8 @@ from .subjects import resolve_subjectQUERY_TYPE = "data_quality_check"+FAILING_STATUSES = (CheckRunStatus.FAILED, CheckRunStatus.ERRORED)+STAGED_FILES_UNREADABLE = "The staged files could not be read, so this data was not audited."@@ -344,13 +348,40 @@ def _record_run(def _update_check(check: DataQualityCheck, outcome: CheckOutcome) -> None:+ ran_at = datetime.now(UTC)check.last_status = outcome.status- check.last_run_at = datetime.now(UTC)+ check.last_run_at = ran_atupdated = ["last_status", "last_run_at", "subject_name", "subject_status", "updated_at"]if outcome.status is CheckRunStatus.PASSED:- check.last_succeeded_at = check.last_run_at+ check.last_succeeded_at = ran_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.updated.append("last_succeeded_at")- check.save(update_fields=updated)+ if outcome.status not in FAILING_STATUSES:+ # Any run that did not fail ends the streak: a pass clears it, and a skipped run (its subject+ # deleted or unresolved) is not a failure to measure from. Cleared unconditionally, unlike the+ # guarded claim below, because only a failing run holds whatever this row said when its batch+ # loaded it -- so only it must defer to the conditional update rather than overwrite a state a+ # concurrent run committed in between.+ check.failing_since = None+ updated.append("failing_since")+ # One transaction, so the row lock the status write takes is held across the streak claim. Apart,+ # the two commit separately and a concurrent pass can land in the gap: the claim then matches+ # failing_since IS NULL and stamps a streak onto a row that already reads passed.+ with transaction.atomic():+ check.save(update_fields=updated)+ if outcome.status in FAILING_STATUSES:+ _claim_failing_streak(check, ran_at)+++def _claim_failing_streak(check: DataQualityCheck, failed_at: datetime) -> None:+ claimed = (+ DataQualityCheck.objects.for_team(check.team_id)+ .filter(id=check.id, failing_since__isnull=True)+ .update(failing_since=failed_at)+ )+ if claimed:+ check.failing_since = failed_at+ return+ check.refresh_from_db(fields=["failing_since"])diff --git a/products/data_quality/backend/migrations/0007_dataqualitycheck_failing_since.py b/products/data_quality/backend/migrations/0007_dataqualitycheck_failing_since.pynew file mode 100644index 000000000000..d354054bd9cb--- /dev/null+++ b/products/data_quality/backend/migrations/0007_dataqualitycheck_failing_since.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.17 on 2026-09-02 18:20++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("data_quality", "0006_dataqualitycheckrun_referenced_subjects"),+ ]++ operations = [+ migrations.AddField(+ model_name="dataqualitycheck",+ name="failing_since",+ field=models.DateTimeField(+ blank=True,+ help_text="When the current streak of failing runs started. Null when the check is not failing.",+ null=True,+ ),+ ),+ ]diff --git a/products/data_quality/backend/migrations/max_migration.txt b/products/data_quality/backend/migrations/max_migration.txtindex 179a1cb55a1d..528470415f5a 100644--- a/products/data_quality/backend/migrations/max_migration.txt+++ b/products/data_quality/backend/migrations/max_migration.txt@@ -1 +1 @@-0006_dataqualitycheckrun_referenced_subjects+0007_dataqualitycheck_failing_sincediff --git a/products/data_quality/backend/models/check.py b/products/data_quality/backend/models/check.pyindex b7dadcbd5603..eaa21a52bd8e 100644--- a/products/data_quality/backend/models/check.py+++ b/products/data_quality/backend/models/check.py@@ -182,6 +182,11 @@ class DataQualityCheck(blank=True,help_text="When the check last passed. Null means it has not passed within the run retention window.",)+ failing_since = models.DateTimeField(+ null=True,+ blank=True,+ help_text="When the current streak of failing runs started. Null when the check is not failing.",+ )fingerprint = models.CharField(max_length=64,diff --git a/products/data_quality/backend/presentation/serializers.py b/products/data_quality/backend/presentation/serializers.pyindex 626bc3c92a84..b46ef5e75c90 100644--- a/products/data_quality/backend/presentation/serializers.py+++ b/products/data_quality/backend/presentation/serializers.py@@ -64,9 +64,15 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):last_succeeded_at = serializers.DateTimeField(read_only=True,allow_null=True,- help_text="When the check last passed, so a failing check can say how long it has been failing. "+ help_text="When the check last passed. Read failing_since for how long a failing check has been failing. ""Null means it has not passed within the run retention window.",)+ failing_since = serializers.DateTimeField(+ read_only=True,+ allow_null=True,+ help_text="When the current streak of failing runs started, so a failing check can say how long "+ "it has been failing. Null when the check is not failing.",+ )subject_status = serializers.CharField(read_only=True,help_text="'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted.",@@ -94,6 +100,7 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):"last_run_at","last_status","last_succeeded_at",+ "failing_since","fingerprint","created_source","ai_model",@@ -110,6 +117,7 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):"last_run_at","last_status","last_succeeded_at",+ "failing_since","fingerprint","created_by","created_at",diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.pyindex 053f45a9dc0b..3ef4dfa4a135 100644--- a/products/data_quality/backend/presentation/views.py+++ b/products/data_quality/backend/presentation/views.py@@ -49,7 +49,7 @@ from .serializers import ()_RECENT_RUNS_LIMIT = 50-_LAST_RUN_FIELDS = ("last_status", "last_run_at", "last_succeeded_at")+_LAST_RUN_FIELDS = ("last_status", "last_run_at", "last_succeeded_at", "failing_since")class _QualityGatedViewSet(TeamAndOrgViewSetMixin):@@ -277,25 +277,37 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewseconfig=data.get("config") or {},**optional,)+ # A create can land on a check that already exists, whose last run read a subject this+ # caller is denied. Blank that run the way an edit does, or the fingerprint match becomes+ # the one way to read history that list hides, retrieve 403s and runs/ empties.+ if not created and self._last_run_is_hidden(check):+ self._redact_last_run(check)return Response(self.get_serializer(check).data,status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,)+ def _last_run_is_hidden(self, check: DataQualityCheck) -> bool:+ return self._can_be_object_denied() and check.id in self._hidden_check_ids([check])++ @staticmethod+ def _redact_last_run(check: DataQualityCheck) -> None:+ for field in _LAST_RUN_FIELDS:+ setattr(check, field, None)+def perform_update(self, serializer: BaseSerializer) -> None:# The candidate definition, not the stored one: an edit that points the check at a new# relationships target or rewrites its custom SQL has to clear that subject too, before it# is saved and the worker starts running it.check = cast(DataQualityCheck, serializer.instance)- redact_last_run = self._can_be_object_denied() and check.id in self._hidden_check_ids([check])+ redact_last_run = self._last_run_is_hidden(check)data = serializer.validated_dataself._require_referenced_subject_access(data.get("check_type", check.check_type), data.get("config", check.config) or {})updated_check = cast(DataQualityCheck, serializer.save())if redact_last_run:- for field in _LAST_RUN_FIELDS:- setattr(updated_check, field, None)+ self._redact_last_run(updated_check)def perform_destroy(self, instance: DataQualityCheck) -> None:api.soft_delete_check(instance)diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.pyindex 3f6e9f84077b..297168928073 100644--- a/products/data_quality/backend/tests/test_api.py+++ b/products/data_quality/backend/tests/test_api.py@@ -600,6 +600,7 @@ class TestDataQualityCheckAPI(APIBaseTest):last_status=CheckRunStatus.FAILED,last_run_at=ran_at,last_succeeded_at=ran_at,+ failing_since=ran_at,)self._deny_the_view()@@ -611,12 +612,58 @@ class TestDataQualityCheckAPI(APIBaseTest):assert edited.json()["last_status"] is Noneassert edited.json()["last_run_at"] is Noneassert edited.json()["last_succeeded_at"] is None+ assert edited.json()["failing_since"] is Noneassert history.status_code == status.HTTP_200_OKassert history.json() == []check.refresh_from_db()assert check.last_status == CheckRunStatus.FAILEDassert check.last_run_at == ran_atassert check.last_succeeded_at == ran_at+ assert check.failing_since == ran_at++ def test_re_creating_a_check_does_not_unlock_the_history_it_used_to_read(self) -> None:+ # A create lands on the existing row when the definition fingerprints the same, so posting a+ # harmless definition is a second way to ask for a check whose last run read the denied+ # "orders" -- one that list hides, retrieve 403s, runs/ empties and patch redacts.+ allowed = self._make_view("customers")+ safe = {"check_type": CheckType.NOT_NULL, "column_name": "id", "config": {}}+ created = self.client.post(f"{self._checks_url(allowed.id)}/", safe)+ assert created.status_code == status.HTTP_201_CREATED, created.json()+ check = DataQualityCheck.objects.for_team(self.team.id).get(id=created.json()["id"])+ api.record_check_run(+ self.team.id,+ suite_run=DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual"),+ quality_check=check,+ subject_type=SubjectType.VIEW,+ subject_uuid=allowed.id,+ subject_name="customers",+ check_type=CheckType.CUSTOM_SQL,+ check_config={"query": "SELECT 1 FROM orders"},+ referenced_subjects=self._pinned(self.view),+ check_fingerprint=check.fingerprint,+ status=CheckRunStatus.FAILED,+ failed_row_count=3,+ compiled_query="SELECT * FROM orders",+ )+ ran_at = now()+ DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id).update(+ last_status=CheckRunStatus.FAILED,+ last_run_at=ran_at,+ last_succeeded_at=ran_at,+ failing_since=ran_at,+ )+ self._deny_the_view()++ recreated = self.client.post(f"{self._checks_url(allowed.id)}/", safe)++ assert recreated.status_code == status.HTTP_200_OK, recreated.json()+ assert recreated.json()["last_status"] is None+ assert recreated.json()["last_run_at"] is None+ assert recreated.json()["last_succeeded_at"] is None+ assert recreated.json()["failing_since"] is None+ check.refresh_from_db()+ assert check.last_status == CheckRunStatus.FAILED+ assert check.failing_since == ran_atdef test_accepted_values_are_stored_as_the_column_holds_them(self) -> None:# The editor can only send strings. Whether the coercion is wired into the create path at alldiff --git a/products/data_quality/backend/tests/test_runner.py b/products/data_quality/backend/tests/test_runner.pyindex b1bef748f3d7..989fa9d2fbd2 100644--- a/products/data_quality/backend/tests/test_runner.py+++ b/products/data_quality/backend/tests/test_runner.py@@ -262,6 +262,52 @@ class TestCheckRunner(BaseTest):stale.refresh_from_db()assert stale.last_succeeded_at == succeeded_at+ def test_the_failing_streak_starts_at_the_first_failure_and_a_pass_ends_it(self) -> None:+ check = self._check()+ failing = _Response(["failure_count", "observed_value"], [3, 3])++ with patch(RUNNER_QUERY, return_value=failing):+ run_check(check, self.suite_run, self.team)+ check.refresh_from_db()+ started_at = check.failing_since+ assert started_at is not None++ with patch(RUNNER_QUERY, return_value=failing):+ run_check(check, self.suite_run, self.team)+ check.refresh_from_db()+ assert check.failing_since == started_at++ 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.failing_since is None++ def test_a_skipped_run_ends_the_failing_streak(self) -> None:+ # A skip means the subject is gone, so the check is no longer failing. Leaving failing_since+ # set would make the next failure measure its age from the pre-skip failure rather than from+ # when it started failing again.+ check = self._check()+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [3, 3])):+ run_check(check, self.suite_run, self.team)+ check.refresh_from_db()+ assert check.failing_since is not None++ self.view.soft_delete()+ outcome = run_check(check, self.suite_run, self.team)++ assert outcome.status == CheckRunStatus.SKIPPED+ check.refresh_from_db()+ assert check.failing_since is None++ def test_an_errored_run_starts_the_failing_streak_too(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+ check.refresh_from_db()+ assert check.failing_since is not None+def test_a_run_snapshots_the_definition_it_executed(self) -> None:# History has to keep reading as what actually ran, even after the definition is edited.check = self._check(diff --git a/products/data_quality/frontend/CheckStatusCell.tsx b/products/data_quality/frontend/CheckStatusCell.tsxindex 45f8e34e06ea..dd3d61f0434b 100644--- a/products/data_quality/frontend/CheckStatusCell.tsx+++ b/products/data_quality/frontend/CheckStatusCell.tsx@@ -9,7 +9,7 @@ import type { DataQualityCheckApi } from './generated/api.schemas'export function CheckStatusCell({check,}: {- check: Pick<DataQualityCheckApi, 'last_status' | 'last_succeeded_at'>+ check: Pick<DataQualityCheckApi, 'last_status' | 'last_succeeded_at' | 'failing_since'>}): JSX.Element {const failingFor = failingForLabel(check)if (!check.last_status) {diff --git a/products/data_quality/frontend/checksConstants.test.ts b/products/data_quality/frontend/checksConstants.test.tsindex 252a310025f8..8beb69fa6e61 100644--- a/products/data_quality/frontend/checksConstants.test.ts+++ b/products/data_quality/frontend/checksConstants.test.ts@@ -7,13 +7,31 @@ describe('checksConstants', () => {// A red tag alone never says "since when", and the answer can be older than any page of run// history, so it has to come off the check rather than be derived from the runs on screen.- it.each<[string, string, string | null, string | null]>([- ['passing checks say nothing', 'passed', '2026-08-19T11:00:00Z', null],- ['checks that never ran say nothing', '', null, null],- ['a failing check counts from its last pass', 'failed', '2026-08-16T12:00:00Z', 'for 3 days'],- ['an erroring check counts too', 'errored', '2026-08-19T09:00:00Z', 'for 3 hours'],- ['a check with no pass on record says so', 'failed', null, 'never passed'],- ])('%s', (_case, lastStatus, lastSucceededAt, expected) => {- expect(failingForLabel({ last_status: lastStatus, last_succeeded_at: lastSucceededAt }, now)).toEqual(expected)+ it.each<[string, string, string | null, string | null, string | null]>([+ ['passing checks say nothing', 'passed', '2026-08-19T11:00:00Z', null, null],+ ['checks that never ran say nothing', '', null, null, null],+ [+ 'a failing check counts from when it started failing, not from its last pass',+ 'failed',+ '2026-08-16T12:00:00Z',+ '2026-08-19T11:55:00Z',+ 'for 5 minutes',+ ],+ ['an erroring check counts too', 'errored', null, '2026-08-19T09:00:00Z', 'for 3 hours'],+ ['a check with no pass on record says so', 'failed', null, null, 'never passed'],+ [+ 'a check failing since before the streak was tracked says nothing',+ 'failed',+ '2026-08-16T12:00:00Z',+ null,+ null,+ ],+ ])('%s', (_case, lastStatus, lastSucceededAt, failingSince, expected) => {+ expect(+ failingForLabel(+ { last_status: lastStatus, last_succeeded_at: lastSucceededAt, failing_since: failingSince },+ now+ )+ ).toEqual(expected)})})diff --git a/products/data_quality/frontend/checksConstants.ts b/products/data_quality/frontend/checksConstants.tsindex 1eedfa586ddf..b61d57df4dae 100644--- a/products/data_quality/frontend/checksConstants.ts+++ b/products/data_quality/frontend/checksConstants.ts@@ -62,16 +62,16 @@ const FAILING_STATUSES = ['failed', 'errored']* raises. Kept short because it sits beside the status tag, which already says it failed.*/export function failingForLabel(- check: Pick<DataQualityCheckApi, 'last_status' | 'last_succeeded_at'>,+ check: Pick<DataQualityCheckApi, 'last_status' | 'last_succeeded_at' | 'failing_since'>,now: Dayjs = dayjs()): string | null {if (!FAILING_STATUSES.includes(check.last_status ?? '')) {return null}- if (!check.last_succeeded_at) {- return 'never passed'+ if (check.failing_since) {+ return `for ${dayjs(check.failing_since).from(now, true)}`}- return `for ${dayjs(check.last_succeeded_at).from(now, true)}`+ return check.last_succeeded_at ? null : 'never passed'}export function checkTypeLabel(checkType: string): string {diff --git a/products/data_quality/frontend/generated/api.schemas.ts b/products/data_quality/frontend/generated/api.schemas.tsindex 07d7bf12e5c4..59b69a544753 100644--- a/products/data_quality/frontend/generated/api.schemas.ts+++ b/products/data_quality/frontend/generated/api.schemas.ts@@ -190,10 +190,15 @@ export interface DataQualityOverviewCheckApi {/** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */readonly last_status: string/**- * When the check last passed, so a failing check can say how long it has been failing. Null means it has not passed within the run retention window.+ * When the check last passed. Read failing_since for how long a failing check has been failing. Null means it has not passed within the run retention window.* @nullable*/readonly last_succeeded_at: string | null+ /**+ * When the current streak of failing runs started, so a failing check can say how long it has been failing. Null when the check is not failing.+ * @nullable+ */+ readonly failing_since: string | null/** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */readonly fingerprint: string/** Whether a human ('user') or an agent ('ai_generated') authored this check.@@ -439,10 +444,15 @@ export interface DataQualityCheckApi {/** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */readonly last_status: string/**- * When the check last passed, so a failing check can say how long it has been failing. Null means it has not passed within the run retention window.+ * When the check last passed. Read failing_since for how long a failing check has been failing. Null means it has not passed within the run retention window.* @nullable*/readonly last_succeeded_at: string | null+ /**+ * When the current streak of failing runs started, so a failing check can say how long it has been failing. Null when the check is not failing.+ * @nullable+ */+ readonly failing_since: string | null/** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */readonly fingerprint: string/** Whether a human ('user') or an agent ('ai_generated') authored this check.@@ -547,10 +557,15 @@ export interface PatchedDataQualityCheckApi {/** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */readonly last_status?: string/**- * When the check last passed, so a failing check can say how long it has been failing. Null means it has not passed within the run retention window.+ * When the check last passed. Read failing_since for how long a failing check has been failing. Null means it has not passed within the run retention window.* @nullable*/readonly last_succeeded_at?: string | null+ /**+ * When the current streak of failing runs started, so a failing check can say how long it has been failing. Null when the check is not failing.+ * @nullable+ */+ readonly failing_since?: string | null/** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */readonly fingerprint?: string/** Whether a human ('user') or an agent ('ai_generated') authored this check.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9aea3f380e0e..639c79158594 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -21514,10 +21514,15 @@ export namespace Schemas {/** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */readonly last_status: string;/**- * When the check last passed, so a failing check can say how long it has been failing. Null means it has not passed within the run retention window.+ * When the check last passed. Read failing_since for how long a failing check has been failing. Null means it has not passed within the run retention window.* @nullable*/readonly last_succeeded_at: string | null;+ /**+ * When the current streak of failing runs started, so a failing check can say how long it has been failing. Null when the check is not failing.+ * @nullable+ */+ readonly failing_since: string | null;/** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */readonly fingerprint: string;/** Whether a human ('user') or an agent ('ai_generated') authored this check.@@ -21707,10 +21712,15 @@ export namespace Schemas {/** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */readonly last_status: string;/**- * When the check last passed, so a failing check can say how long it has been failing. Null means it has not passed within the run retention window.+ * When the check last passed. Read failing_since for how long a failing check has been failing. Null means it has not passed within the run retention window.* @nullable*/readonly last_succeeded_at: string | null;+ /**+ * When the current streak of failing runs started, so a failing check can say how long it has been failing. Null when the check is not failing.+ * @nullable+ */+ readonly failing_since: string | null;/** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */readonly fingerprint: string;/** Whether a human ('user') or an agent ('ai_generated') authored this check.@@ -60968,10 +60978,15 @@ export namespace Schemas {/** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */readonly last_status?: string;/**- * When the check last passed, so a failing check can say how long it has been failing. Null means it has not passed within the run retention window.+ * When the check last passed. Read failing_since for how long a failing check has been failing. Null means it has not passed within the run retention window.* @nullable*/readonly last_succeeded_at?: string | null;+ /**+ * When the current streak of failing runs started, so a failing check can say how long it has been failing. Null when the check is not failing.+ * @nullable+ */+ readonly failing_since?: string | null;/** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */readonly fingerprint?: string;/** Whether a human ('user') or an agent ('ai_generated') authored this check.