: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): make failing rows debuggable after a gated block (#105399)
Thiago Salvatored4218652bc61
diff --git a/docs/internal/data-quality-checks.md b/docs/internal/data-quality-checks.mdindex 7fbeb070d6d8..9421607a0f50 100644--- a/docs/internal/data-quality-checks.md+++ b/docs/internal/data-quality-checks.md@@ -62,6 +62,8 @@ Notification recipient checks retain the existing global warehouse-resource poliCatalog access is a project permission resource. Notification visibility follows that permission, including after access is revoked.+A run under the materialization gate sets `audited_staged_refresh`, including a run that errored before it could read the staged files. Check `status` and `error` before treating the refresh as audited. The stored failing-rows query cannot name the view, because the SQL editor resolves that name to the published table, which after a block is still the previous version. So the query holds the view's definition in a `WITH` clause and reads the view's source tables. Those sources can change after the run, so a replay can return different rows than the run counted. When the view's definition cannot be read, the run stores no query.+## Models overviewThe models overview reports one status for the whole project. It shows the status panel only when the model list and the check list have both answered, and when no model and no check needs attention. A request that failed is reported as a failure, so an unanswered request never reads as an all-clear.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 71598c194476..44e395de6050 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2729,9 +2729,9 @@ snapshots:data-catalog-metric-tests--unsupported-with-checks--light:hash: v1.k794b7964.64e9162a5dd7bc47a1667f13d8c77b4d1f00c6e15c70169ab4d4ffc588dd2112.j2HS8sjcKIg0QXaZ9PLel28BVD4vayBEBRzrHVO-dlIdata-quality-check-runs-table--every-check-type--dark:- hash: v1.k794b7964.8cdbb71c619659feb900c816afd412ec8fe0a99c8b44fc956275282ef56b3c3e.tMGIu_lh3Uf5WvR8QXUP3iSTRKFPFS2u9Y6Wl8Ouay4+ hash: v1.k794b7964.58b1a7ef739ee0fbd3e32caf4cb28f8c81711efde8c25e99078e3b50cae46bc8.gIoFuHrcjiy-DhCsfa6kuyW36xY3EwX5EqxNTkQFZq8data-quality-check-runs-table--every-check-type--light:- hash: v1.k794b7964.e90e41b601b4690332e483ff2a1d4df0cb8456d1c92f92a97ef25cfe5f87e182.8HRaicZOtyvYQWwDDffAr_NGSMuQOfySkIb4xgd9K5Q+ hash: v1.k794b7964.dcb1f39625722782dbed6ce97b61684a7664c7d08034cefbb72cb32b6e97e3f3.c33MSTfBglNRA-pjdWyRCUxT8tOVGzg5lGO2CxSEyRcdata-warehouse-destinationlist--both-selected--dark:hash: v1.k794b7964.5da0169833ea8b87e6d903cb4fc0f4d629a1b1db09149c5fb7c450ef312641a0.MH4OyaTjM18a4cpxtpCHPVm1QWWajZL5cz4NlzbJag0data-warehouse-destinationlist--both-selected--light:diff --git a/posthog/hogql/printer/hogql.py b/posthog/hogql/printer/hogql.pyindex 780f67ba1c4e..58dcd51c6863 100644--- a/posthog/hogql/printer/hogql.py+++ b/posthog/hogql/printer/hogql.py@@ -109,7 +109,10 @@ class HogQLPrinter(BasePrinter):return self._print_identifier(table_type.table.to_printed_hogql())def _render_untyped_join_expr(self, node: ast.JoinExpr) -> list[str]:- parts = [self.visit(node.table)]+ table = self.visit(node.table)+ if node.table_args is not None:+ table = f"{table}({', '.join(self.visit(arg) for arg in node.table_args)})"+ parts = [table]if node.alias is not None:parts.append(f"AS {self._print_identifier(node.alias)}")return partsdiff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex 7d467d7f3430..0a3cd0e5bd28 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -2309,6 +2309,15 @@ class TestPrinter(BaseTest):)self._assert_query_error("select 1 from other", "Unknown table `other`.")+ @parameterized.expand(+ [+ ("SELECT * FROM numbers(10)",),+ ("SELECT * FROM numbers(2, 5) AS n",),+ ]+ )+ def test_unresolved_hogql_keeps_table_function_arguments(self, query: str) -> None:+ assert parse_select(query).to_hogql() == query+def test_select_from_placeholder(self):self.assertEqual(self._select(diff --git a/products/data_quality/backend/logic/compiler.py b/products/data_quality/backend/logic/compiler.pyindex 059790586ca7..d794384d7217 100644--- a/products/data_quality/backend/logic/compiler.py+++ b/products/data_quality/backend/logic/compiler.py@@ -40,10 +40,12 @@ def compile_check(parsed = spec.validate(config, column_name)plan = _windowed(spec.build(subject, column_name, parsed, related_subject), check_type, subject, parsed)query = _aggregate(plan)+ failing_rows = plan.diagnostic_rows or plan.failing_rowsreturn CompiledCheck(query=query,- printed_query=_print(query),- printed_failing_rows_query=_print(plan.diagnostic_rows or plan.failing_rows),+ printed_query=print_check_query(query),+ printed_failing_rows_query=print_check_query(failing_rows),+ failing_rows=failing_rows,evaluation=plan.evaluation,)@@ -62,7 +64,7 @@ def _windowed(plan: CheckPlan, check_type: str, subject: SubjectRef, config: Anyreturn plan-def _print(query: "ast.SelectQuery | ast.SelectSetQuery") -> str:+def print_check_query(query: "ast.SelectQuery | ast.SelectSetQuery") -> str:# limit_top_select=False: the aggregate is a single row anyway, and the failing-rows form is# stored for a human to re-run, so a synthetic LIMIT would misrepresent what the check examined.return print_prepared_ast(diff --git a/products/data_quality/backend/logic/contracts.py b/products/data_quality/backend/logic/contracts.pyindex ca99efdc2b82..6439a299e1fb 100644--- a/products/data_quality/backend/logic/contracts.py+++ b/products/data_quality/backend/logic/contracts.py@@ -85,4 +85,5 @@ class CompiledCheck:query: "ast.SelectQuery"printed_query: strprinted_failing_rows_query: str+ failing_rows: "ast.SelectQuery | ast.SelectSetQuery"evaluation: Evaluationdiff --git a/products/data_quality/backend/logic/run_records.py b/products/data_quality/backend/logic/run_records.pyindex 0b03b0786f8d..ed793796482b 100644--- a/products/data_quality/backend/logic/run_records.py+++ b/products/data_quality/backend/logic/run_records.py@@ -31,6 +31,7 @@ def record_check_run(failed_row_count: int | None = None,observed_value: float | None = None,compiled_query: str = "",+ audited_staged_refresh: bool = False,error: str = "",duration_ms: int | None = None,started_at: datetime | None = None,@@ -54,6 +55,7 @@ def record_check_run(failed_row_count=failed_row_count,observed_value=observed_value,compiled_query=compiled_query,+ audited_staged_refresh=audited_staged_refresh,error=error,duration_ms=duration_ms,started_at=started_at,diff --git a/products/data_quality/backend/logic/runner.py b/products/data_quality/backend/logic/runner.pyindex fd0fd5c18811..0c821b262145 100644--- a/products/data_quality/backend/logic/runner.py+++ b/products/data_quality/backend/logic/runner.py@@ -23,6 +23,7 @@ if TYPE_CHECKING:from posthog.hogql.database.database import Databasefrom posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.exceptions_capture import capture_exceptionfrom posthog.models.scoping import team_scopefrom posthog.models.team import Teamfrom posthog.models.user import User@@ -32,7 +33,7 @@ from ..models import DataQualityCheck, DataQualitySuiteRunfrom .compiler import compile_check, related_subject_reffrom .contracts import CompiledCheck, Evaluation, SubjectReffrom .run_records import record_check_run-from .staged_audit import StagedSubjectOverride, build_staged_database+from .staged_audit import StagedSubjectOverride, build_staged_database, replayable_failing_rows_queryfrom .subject_access import check_type_reads_beyond_subject, pin_referenced_subjectsfrom .subjects import resolve_subjectfrom .types.common import within_bounds@@ -58,6 +59,7 @@ class CheckOutcome:compiled_query: str = ""error: str = ""referenced_subjects: list[dict[str, str]] | None | _ReferenceState = _ReferenceState.NOT_SUPPLIED+ audited_staged_refresh: bool = Falsedef run_check(@@ -81,6 +83,7 @@ def run_check(outcome = _execute(check, suite_run, team, staged, staged_database_cache)except Exception as err:outcome = CheckOutcome(status=CheckRunStatus.ERRORED, error=str(err))+ outcome = replace(outcome, audited_staged_refresh=staged is not None)duration_ms = int((time.monotonic() - monotonic_start) * 1000)finished_at = datetime.now(UTC)@@ -95,9 +98,10 @@ def record_unrunnable_check(suite_run: DataQualitySuiteRun,team: Team,reason: str,+ audited_staged_refresh: bool = False,) -> 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)+ outcome = CheckOutcome(status=CheckRunStatus.ERRORED, error=reason, audited_staged_refresh=audited_staged_refresh)finished_at = datetime.now(UTC)with team_scope(team.id):_record_run(check, suite_run, outcome, finished_at, finished_at, duration_ms=0)@@ -218,6 +222,8 @@ def _execute()if staged is not None and subject.subject_type == SubjectType.METRIC:return CheckOutcome(status=CheckRunStatus.ERRORED, error="Metric checks cannot audit staged data.")+ if staged is not None:+ compiled = _replayable_against_sources(compiled, team, staged)referenced_subjects = pin_referenced_subjects(team.id, check.check_type, check.config, subject=subject)try:outcome = _execute_compiled(check, subject, compiled, team, authorization, staged, staged_database_cache)@@ -230,6 +236,15 @@ def _execute(return replace(outcome, referenced_subjects=referenced_subjects)+def _replayable_against_sources(compiled: CompiledCheck, team: Team, staged: StagedSubjectOverride) -> CompiledCheck:+ try:+ replayable = replayable_failing_rows_query(team.pk, staged.saved_query_id, compiled.failing_rows)+ except Exception as err:+ capture_exception(err)+ replayable = None+ return replace(compiled, printed_failing_rows_query=replayable or "")++def _execute_compiled(check: DataQualityCheck,subject: SubjectRef,@@ -362,6 +377,7 @@ def _record_run(failed_row_count=outcome.failed_row_count,observed_value=outcome.observed_value,compiled_query=outcome.compiled_query,+ audited_staged_refresh=outcome.audited_staged_refresh,error=outcome.error,duration_ms=duration_ms,started_at=started_at,diff --git a/products/data_quality/backend/logic/staged_audit.py b/products/data_quality/backend/logic/staged_audit.pyindex 1b82d72a9e18..952db1fdd34e 100644--- a/products/data_quality/backend/logic/staged_audit.py+++ b/products/data_quality/backend/logic/staged_audit.py@@ -1,15 +1,20 @@"""Point a subject's table at staged (unpublished) files, for write-audit-publish check runs."""-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom typing import TYPE_CHECKINGfrom uuid import UUID+from posthog.hogql import astfrom posthog.hogql.database.database import Databasefrom posthog.hogql.database.s3_table import S3Table+from posthog.hogql.errors import BaseHogQLErrorfrom posthog.hogql.modifiers import create_default_modifiers_for_team+from posthog.hogql.parser import parse_selectfrom products.data_modeling.backend.facade import api as data_modeling_facade+from .compiler import print_check_query+if TYPE_CHECKING:from posthog.models.team import Teamfrom posthog.models.user import User@@ -57,3 +62,37 @@ def build_staged_database(return Nonetable.queryable_folder = staged_queryable_folderreturn database+++def replayable_failing_rows_query(+ team_id: int,+ saved_query_id: str | UUID,+ failing_rows: "ast.SelectQuery | ast.SelectSetQuery",+) -> str | None:+ """The failing-rows query with the view's definition inlined as a CTE, or None when the view cannot be read."""+ view_cte = _view_definition_cte(team_id, saved_query_id)+ if view_cte is None:+ return None+ return print_check_query(_with_cte(failing_rows, view_cte))+++def _view_definition_cte(team_id: int, saved_query_id: str | UUID) -> ast.CTE | None:+ summary = data_modeling_facade.get_saved_query_summary(team_id, saved_query_id)+ definition = data_modeling_facade.get_saved_query_sql(team_id, saved_query_id)+ if summary is None or definition is None:+ return None+ try:+ parsed = parse_select(definition)+ except BaseHogQLError:+ return None+ return ast.CTE(name=summary.name, expr=parsed, cte_type="subquery")+++def _with_cte(query: "ast.SelectQuery | ast.SelectSetQuery", cte: ast.CTE) -> ast.SelectQuery:+ if isinstance(query, ast.SelectSetQuery) or cte.name in (query.ctes or {}):+ return ast.SelectQuery(+ select=[ast.Field(chain=["*"])],+ select_from=ast.JoinExpr(table=query),+ ctes={cte.name: cte},+ )+ return replace(query, ctes={cte.name: cte, **(query.ctes or {})})diff --git a/products/data_quality/backend/migrations/0015_dataqualitycheckrun_audited_staged_refresh.py b/products/data_quality/backend/migrations/0015_dataqualitycheckrun_audited_staged_refresh.pynew file mode 100644index 000000000000..ee68bfe37f0e--- /dev/null+++ b/products/data_quality/backend/migrations/0015_dataqualitycheckrun_audited_staged_refresh.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.17 on 2026-09-23 16:11++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("data_quality", "0014_validate_posthog_table_binding"),+ ]++ operations = [+ migrations.AddField(+ model_name="dataqualitycheckrun",+ name="audited_staged_refresh",+ field=models.BooleanField(+ db_default=False,+ default=False,+ help_text="True when the run audited a refresh that was staged but not yet published, under the materialization gate.",+ ),+ ),+ ]diff --git a/products/data_quality/backend/migrations/max_migration.txt b/products/data_quality/backend/migrations/max_migration.txtindex 6e44e5a4dc7a..17e10443e9ea 100644--- a/products/data_quality/backend/migrations/max_migration.txt+++ b/products/data_quality/backend/migrations/max_migration.txt@@ -1 +1 @@-0014_validate_posthog_table_binding+0015_dataqualitycheckrun_audited_staged_refreshdiff --git a/products/data_quality/backend/models/check_run.py b/products/data_quality/backend/models/check_run.pyindex 9475f3b96f67..e9ed5e858e4a 100644--- a/products/data_quality/backend/models/check_run.py+++ b/products/data_quality/backend/models/check_run.py@@ -148,6 +148,11 @@ class DataQualityCheckRun(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFieblank=True,help_text="HogQL selecting the failing rows. Re-run it to see them. Cleared by retention after 30 days.",)+ audited_staged_refresh = models.BooleanField(+ default=False,+ db_default=False,+ help_text="True when the run audited a refresh that was staged but not yet published, under the materialization gate.",+ )error = models.TextField(blank=True, help_text="Compilation or execution failure, for status=errored.")duration_ms = models.IntegerField(null=True, blank=True)diff --git a/products/data_quality/backend/presentation/serializers.py b/products/data_quality/backend/presentation/serializers.pyindex 8535d23195a6..eed8ecace7fa 100644--- a/products/data_quality/backend/presentation/serializers.py+++ b/products/data_quality/backend/presentation/serializers.py@@ -420,6 +420,7 @@ class DataQualityCheckRunSerializer(serializers.ModelSerializer):"failed_row_count","observed_value","compiled_query",+ "audited_staged_refresh","error","duration_ms","started_at",@@ -430,7 +431,12 @@ class DataQualityCheckRunSerializer(serializers.ModelSerializer):extra_kwargs = {"failed_row_count": {"help_text": "Rows violating the assertion. Null for bounds checks like row_count."},"observed_value": {"help_text": "The check's headline number, recorded on passes too."},- "compiled_query": {"help_text": "The HogQL that ran. Re-run it to see the offending rows."},+ "compiled_query": {+ "help_text": "HogQL selecting the failing rows. Re-run it to see them. For a run that audited a "+ "staged refresh it inlines the view's definition, so it reads the source tables rather than "+ "the published table. Empty when there is nothing to replay: retention cleared it, or a staged "+ "run could not build its replay query."+ },"error": {"help_text": "Compilation or execution failure, when status is 'errored'."},}diff --git a/products/data_quality/backend/temporal/activities/run_check_batch.py b/products/data_quality/backend/temporal/activities/run_check_batch.pyindex 054fd5c35835..71945cfe022f 100644--- a/products/data_quality/backend/temporal/activities/run_check_batch.py+++ b/products/data_quality/backend/temporal/activities/run_check_batch.py@@ -32,7 +32,7 @@ def _record_unaudited_batch("""Error every check in the batch, leaving ``failed_blocking`` at zero so a gate publishes."""errored = 0for check in checks:- record_unrunnable_check(check, suite_run, team, STAGED_FILES_UNREADABLE)+ record_unrunnable_check(check, suite_run, team, STAGED_FILES_UNREADABLE, audited_staged_refresh=True)errored += 1LOGGER.warning("Could not audit staged files", suite_run_id=str(suite_run.id), checks=errored)return BatchOutcome(errored=errored)diff --git a/products/data_quality/backend/tests/test_run_check_suite.py b/products/data_quality/backend/tests/test_run_check_suite.pyindex 4cb6ae38a3ef..13603430dbff 100644--- a/products/data_quality/backend/tests/test_run_check_suite.py+++ b/products/data_quality/backend/tests/test_run_check_suite.py@@ -252,6 +252,7 @@ class TestCheckSuiteActivities(BaseTest):run = DataQualityCheckRun.objects.for_team(self.team.id).get(suite_run_id=prepared.suite_run_id)assert run.status == CheckRunStatus.ERROREDassert "staged files" in run.error+ assert run.audited_staged_refreshdef _fail_checks(self, checks: list[DataQualityCheck]) -> str:suite_run_id = self._prepare(created_by_id=self.user.id).suite_run_iddiff --git a/products/data_quality/backend/tests/test_runner.py b/products/data_quality/backend/tests/test_runner.pyindex 3d3d4ec57c75..63ef15775c24 100644--- a/products/data_quality/backend/tests/test_runner.py+++ b/products/data_quality/backend/tests/test_runner.py@@ -25,10 +25,13 @@ from products.data_quality.backend.facade.enums import (SuiteRunTrigger,)from products.data_quality.backend.logic.runner import run_check+from products.data_quality.backend.logic.staged_audit import StagedSubjectOverridefrom products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun-from products.warehouse_sources.backend.facade.models import DataWarehouseTable+from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTableRUNNER_QUERY = "products.data_quality.backend.logic.runner.execute_hogql_query"+STAGED_FOLDER = "query_2000000000000"+SAVED_QUERY_SQL = "products.data_modeling.backend.logic.saved_query_reads.get_saved_query_sql"CREATE_NOTIFICATION = "products.data_quality.backend.logic.notifications.create_notification"@@ -48,6 +51,20 @@ class TestCheckRunner(BaseTest):team=self.team, trigger=SuiteRunTrigger.MANUAL)+ def _materialize_view(self) -> None:+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="_key", access_secret="_secret")+ self.view.table = DataWarehouseTable.objects.create(+ name="orders",+ team=self.team,+ columns={"customer_id": "String"},+ credential=credential,+ format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,+ url_pattern="http://localhost:19000/bucket/team_1_model_x/modeling/orders",+ queryable_folder="query_1000000000000",+ )+ self.view.is_materialized = True+ self.view.save()+def _check(self, **kwargs) -> DataQualityCheck:defaults = {"team": self.team,@@ -254,13 +271,41 @@ class TestCheckRunner(BaseTest):assert tags.data_quality_subject_type == SubjectType.VIEWassert tags.data_quality_subject_id == str(self.view.id)- def test_the_stored_query_selects_failing_rows(self) -> None:+ @parameterized.expand(+ [+ ("published", False, "SELECT * FROM orders WHERE isNull(customer_id)"),+ (+ "staged",+ True,+ "WITH orders AS (SELECT 1 AS customer_id) SELECT * FROM orders WHERE isNull(customer_id)",+ ),+ ]+ )+ def test_the_stored_query_selects_failing_rows(self, _name: str, audit_staged: bool, expected: str) -> None:+ self._materialize_view()check = self._check()+ staged = (+ StagedSubjectOverride(saved_query_id=str(self.view.id), queryable_folder=STAGED_FOLDER)+ if audit_staged+ else None+ )with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [3, 3])):- run_check(check, self.suite_run, self.team)+ run_check(check, self.suite_run, self.team, staged=staged)run = DataQualityCheckRun.objects.for_team(self.team.id).get(quality_check=check)- assert run.compiled_query == "SELECT * FROM orders WHERE isNull(customer_id)"+ assert (run.compiled_query, run.audited_staged_refresh) == (expected, audit_staged)++ def test_a_staged_run_still_audits_when_its_replay_query_cannot_be_built(self) -> None:+ self._materialize_view()+ check = self._check()+ staged = StagedSubjectOverride(saved_query_id=str(self.view.id), queryable_folder=STAGED_FOLDER)+ with (+ patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [3, 3])),+ patch(SAVED_QUERY_SQL, side_effect=RuntimeError("database unavailable")),+ ):+ outcome = run_check(check, self.suite_run, self.team, staged=staged)++ assert (outcome.status, outcome.failed_row_count, outcome.compiled_query) == (CheckRunStatus.FAILED, 3, "")@parameterized.expand([diff --git a/products/data_quality/backend/tests/test_staged_audit.py b/products/data_quality/backend/tests/test_staged_audit.pyindex 7c7be57879ca..115b75225acd 100644--- a/products/data_quality/backend/tests/test_staged_audit.py+++ b/products/data_quality/backend/tests/test_staged_audit.py@@ -1,5 +1,9 @@+from typing import Any+from posthog.test.base import BaseTest+from parameterized import parameterized+from posthog.hogql.context import HogQLContextfrom posthog.hogql.printer.utils import prepare_and_print_ast@@ -7,7 +11,7 @@ from products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_quality.backend.facade.api import compile_checkfrom products.data_quality.backend.facade.enums import CheckType, SubjectTypefrom products.data_quality.backend.logic.contracts import SubjectRef-from products.data_quality.backend.logic.staged_audit import build_staged_database+from products.data_quality.backend.logic.staged_audit import build_staged_database, replayable_failing_rows_queryfrom products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -37,17 +41,21 @@ class TestStagedAudit(BaseTest):status=DataWarehouseSavedQuery.Status.COMPLETED,)- def _compiled_check_urls(self, view: DataWarehouseSavedQuery, staged_folder: str) -> list[str]:- database = build_staged_database(self.team, view.id, staged_folder)- assert database is not None- subject = SubjectRef(+ def _subject(self, view: DataWarehouseSavedQuery) -> SubjectRef:+ return SubjectRef(subject_type=SubjectType.VIEW,subject_uuid=str(view.id),name=view.name,queryable_name=view.name,exists=True,)- compiled = compile_check(check_type=CheckType.NOT_NULL, subject=subject, column_name="customer_id", config={})++ def _compiled_check_urls(self, view: DataWarehouseSavedQuery, staged_folder: str) -> list[str]:+ database = build_staged_database(self.team, view.id, staged_folder)+ assert database is not None+ compiled = compile_check(+ check_type=CheckType.NOT_NULL, subject=self._subject(view), column_name="customer_id", config={}+ )context = HogQLContext(team_id=self.team.pk, team=self.team, database=database, enable_select_queries=True)prepare_and_print_ast(compiled.query, context=context, dialect="clickhouse")# S3 urls print as sensitive parameters, so the staged path lands in context values.@@ -70,3 +78,47 @@ class TestStagedAudit(BaseTest):)assert build_staged_database(self.team, view.id, STAGED_FOLDER) is None++ @parameterized.expand(+ [+ (+ "a_generated_check",+ CheckType.NOT_NULL,+ "customer_id",+ {},+ "WITH orders AS (SELECT 1 AS customer_id) SELECT * FROM orders WHERE isNull(customer_id)",+ ),+ (+ "custom_sql_naming_the_view",+ CheckType.CUSTOM_SQL,+ "",+ {"query": "SELECT customer_id FROM orders WHERE customer_id = 2"},+ "WITH orders AS (SELECT 1 AS customer_id) SELECT customer_id FROM orders WHERE equals(customer_id, 2)",+ ),+ (+ "custom_sql_union",+ CheckType.CUSTOM_SQL,+ "",+ {"query": "SELECT customer_id FROM orders UNION ALL SELECT customer_id FROM orders"},+ "WITH orders AS (SELECT 1 AS customer_id) SELECT * FROM "+ "(SELECT customer_id FROM orders UNION ALL SELECT customer_id FROM orders)",+ ),+ (+ "custom_sql_whose_cte_shadows_the_view",+ CheckType.CUSTOM_SQL,+ "",+ {"query": "WITH orders AS (SELECT customer_id FROM orders) SELECT customer_id FROM orders"},+ "WITH orders AS (SELECT 1 AS customer_id) SELECT * FROM "+ "(WITH orders AS (SELECT customer_id FROM orders) SELECT customer_id FROM orders)",+ ),+ ]+ )+ def test_the_stored_query_for_a_staged_run_inlines_the_view_definition(+ self, _name: str, check_type: CheckType, column_name: str, config: dict[str, Any], expected: str+ ) -> None:+ view = self._materialized_view()+ compiled = compile_check(+ check_type=check_type, subject=self._subject(view), column_name=column_name, config=config+ )++ assert replayable_failing_rows_query(self.team.pk, view.id, compiled.failing_rows) == expecteddiff --git a/products/data_quality/frontend/CheckRunsTable.stories.tsx b/products/data_quality/frontend/CheckRunsTable.stories.tsxindex ebe2714ce5ad..fda383ca8672 100644--- a/products/data_quality/frontend/CheckRunsTable.stories.tsx+++ b/products/data_quality/frontend/CheckRunsTable.stories.tsx@@ -19,6 +19,7 @@ const BASE_RUN: DataQualityCheckRunApi = {failed_row_count: 0,observed_value: 0,compiled_query: 'SELECT count() FROM orders',+ audited_staged_refresh: false,error: '',duration_ms: 1200,started_at: '2026-09-04T09:00:00Z',@@ -46,7 +47,14 @@ const RUNS_OF_EVERY_TYPE: DataQualityCheckRunApi[] = [failed_row_count: null,observed_value: 2493355,}),- run({ check_type: 'not_null', column_name: 'email', status: 'failed', failed_row_count: 7, observed_value: 7 }),+ run({+ check_type: 'not_null',+ column_name: 'email',+ status: 'failed',+ failed_row_count: 7,+ observed_value: 7,+ audited_staged_refresh: true,+ }),run({ check_type: 'unique', column_name: 'order_id', status: 'failed', failed_row_count: 1, observed_value: 1 }),run({check_type: 'accepted_values',diff --git a/products/data_quality/frontend/CheckRunsTable.test.tsx b/products/data_quality/frontend/CheckRunsTable.test.tsxindex 3e369ebd47e9..abbd916a3b95 100644--- a/products/data_quality/frontend/CheckRunsTable.test.tsx+++ b/products/data_quality/frontend/CheckRunsTable.test.tsx@@ -23,6 +23,7 @@ const PASSING_METRIC_RUN: DataQualityCheckRunApi = {failed_row_count: 0,observed_value: 0,compiled_query: 'SELECT count() FROM signups',+ audited_staged_refresh: false,error: '',duration_ms: 20,started_at: null,@@ -66,6 +67,13 @@ describe('CheckRunsTable', () => {expect(screen.getByText('7 rows returned')).toBeInTheDocument()expect(screen.getByText('Unknown column signups')).toBeInTheDocument()expect(screen.queryByText('Failed rows')).not.toBeInTheDocument()+ expect(screen.queryByText('Unpublished refresh')).not.toBeInTheDocument()+ })++ it('marks a run that checked a refresh before it was published', () => {+ initKeaTests()+ render(<CheckRunsTable runs={[metricRun({ status: 'failed', audited_staged_refresh: true })]} />)+ expect(screen.getByText('Unpublished refresh')).toBeInTheDocument()})it('shows a freshness run as how old its newest row is', () => {diff --git a/products/data_quality/frontend/CheckRunsTable.tsx b/products/data_quality/frontend/CheckRunsTable.tsxindex 9a8b455219f2..b3e8a04a1530 100644--- a/products/data_quality/frontend/CheckRunsTable.tsx+++ b/products/data_quality/frontend/CheckRunsTable.tsx@@ -4,7 +4,13 @@ import { TZLabel } from 'lib/components/TZLabel'import { LemonTableColumn } from 'lib/lemon-ui/LemonTable'import { humanFriendlyDuration } from 'lib/utils/durations'-import { CHECK_STATUS_TAG_TYPES, byStatusAttention, checkRunDisplayName, runResultCell } from './checksConstants'+import {+ CHECK_STATUS_TAG_TYPES,+ UNPUBLISHED_REFRESH_EXPLANATION,+ byStatusAttention,+ checkRunDisplayName,+ runResultCell,+} from './checksConstants'import type { DataQualityCheckRunApi } from './generated/api.schemas'type CheckRunColumn = LemonTableColumn<DataQualityCheckRunApi, keyof DataQualityCheckRunApi | undefined>@@ -19,7 +25,16 @@ const OUTCOME_COLUMNS: CheckRunColumn[] = [{title: 'Status',key: 'status',- render: (_, run) => <LemonTag type={CHECK_STATUS_TAG_TYPES[run.status] ?? 'default'}>{run.status}</LemonTag>,+ render: (_, run) => (+ <div className="flex flex-wrap items-center gap-1">+ <LemonTag type={CHECK_STATUS_TAG_TYPES[run.status] ?? 'default'}>{run.status}</LemonTag>+ {run.audited_staged_refresh ? (+ <Tooltip title={UNPUBLISHED_REFRESH_EXPLANATION}>+ <LemonTag type="muted">Unpublished refresh</LemonTag>+ </Tooltip>+ ) : null}+ </div>+ ),},{title: 'Started',diff --git a/products/data_quality/frontend/checksConstants.ts b/products/data_quality/frontend/checksConstants.tsindex 5d8f0b477cac..0749b5648402 100644--- a/products/data_quality/frontend/checksConstants.ts+++ b/products/data_quality/frontend/checksConstants.ts@@ -43,6 +43,12 @@ export function byStatusAttention()}+export const UNPUBLISHED_REFRESH_EXPLANATION =+ 'This run checked a refresh before it was published. The failing rows query rebuilds the view from its source tables, so the rows can differ from that refresh.'++export const UNPUBLISHED_REFRESH_QUERY_UNAVAILABLE =+ "The latest run checked a refresh before it was published, and its failing rows query isn't available. Run the view again to check the new data."+export const SUITE_RUN_STATUS_TAG_TYPES: Record<string, LemonTagType> = {running: 'primary',completed: 'success',diff --git a/products/data_quality/frontend/generated/api.schemas.ts b/products/data_quality/frontend/generated/api.schemas.tsindex ae6ae539eb9c..06e8c579d809 100644--- a/products/data_quality/frontend/generated/api.schemas.ts+++ b/products/data_quality/frontend/generated/api.schemas.ts@@ -666,8 +666,10 @@ export interface DataQualityCheckRunApi {* @nullable*/readonly observed_value: number | null- /** The HogQL that ran. Re-run it to see the offending rows. */+ /** HogQL selecting the failing rows. Re-run it to see them. For a run that audited a staged refresh it inlines the view's definition, so it reads the source tables rather than the published table. Empty when there is nothing to replay: retention cleared it, or a staged run could not build its replay query. */readonly compiled_query: string+ /** True when the run audited a refresh that was staged but not yet published, under the materialization gate. */+ readonly audited_staged_refresh: boolean/** Compilation or execution failure, when status is 'errored'. */readonly error: string/** @nullable */diff --git a/products/data_quality/frontend/openFailingRows.ts b/products/data_quality/frontend/openFailingRows.tsindex 1fcc695bee62..63e48b2fd129 100644--- a/products/data_quality/frontend/openFailingRows.ts+++ b/products/data_quality/frontend/openFailingRows.ts@@ -4,8 +4,9 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { urls } from 'scenes/urls'import { apiErrorDetail } from './checksApi'+import { UNPUBLISHED_REFRESH_EXPLANATION, UNPUBLISHED_REFRESH_QUERY_UNAVAILABLE } from './checksConstants'import type { DataQualityCheckRunApi } from './generated/api.schemas'-import { latestFailingRowsQuery } from './suiteRuns'+import { latestRunWithQuery } from './suiteRuns'/*** Send the caller to this check's failing rows in the SQL editor.@@ -32,8 +33,8 @@ export async function openFailingRowsInSqlEditor({return}}- const query = latestFailingRowsQuery(runs)- if (!query) {+ const run = latestRunWithQuery(runs)+ if (!run) {lemonToast.info(runs.length? 'The query for this check is no longer kept. Run the check to see its failing rows.'@@ -41,5 +42,12 @@ export async function openFailingRowsInSqlEditor({)return}- router.actions.push(urls.sqlEditor({ query }))+ if (!run.compiled_query) {+ lemonToast.info(UNPUBLISHED_REFRESH_QUERY_UNAVAILABLE)+ return+ }+ if (run.audited_staged_refresh) {+ lemonToast.info(UNPUBLISHED_REFRESH_EXPLANATION)+ }+ router.actions.push(urls.sqlEditor({ query: run.compiled_query }))}diff --git a/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts b/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.tsindex 09ab3a5359ad..784c4bbf9ec7 100644--- a/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts+++ b/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts@@ -516,15 +516,27 @@ describe('dataQualityOverviewLogic', () => {expect(logic.values.isRunning).toBe(false)})- it.each<[string, Record<string, string>[], string | null]>([+ it.each<[string, Record<string, string | boolean>[], string | null, boolean]>([// Retention clears the compiled query of older runs first, so "latest" is not always [0].['the newest run that still has one',[{ compiled_query: 'SELECT 2' }, { compiled_query: 'SELECT 1' }],'SELECT 2',+ false,],- ['past runs whose query was cleared', [{ compiled_query: '' }, { compiled_query: 'SELECT 1' }], 'SELECT 1'],- ])('opens the failing rows of %s', async (_case, runs, expected) => {+ [+ 'past runs whose query was cleared',+ [{ compiled_query: '' }, { compiled_query: 'SELECT 1' }],+ 'SELECT 1',+ false,+ ],+ [+ 'a run that checked an unpublished refresh',+ [{ compiled_query: 'WITH orders AS (SELECT 1) SELECT * FROM orders', audited_staged_refresh: true }],+ 'WITH orders AS (SELECT 1) SELECT * FROM orders',+ true,+ ],+ ])('opens the failing rows of %s', async (_case, runs, expected, explained) => {;(dataQualityChecksRunsList as jest.Mock).mockResolvedValue(runs)await mountLogic()@@ -533,11 +545,16 @@ describe('dataQualityOverviewLogic', () => {expect(router.values.location.pathname).toMatch(/\/sql$/)expect(router.values.searchParams.open_query).toEqual(expected)+ expect(lemonToast.info).toHaveBeenCalledTimes(explained ? 1 : 0)})- it.each<[string, Record<string, string>[]]>([+ it.each<[string, Record<string, string | boolean>[]]>([['the check has never run', []],['every run has lost its query to retention', [{ compiled_query: '' }]],+ [+ 'the newest run checked an unpublished refresh but has no query',+ [{ compiled_query: '', audited_staged_refresh: true }, { compiled_query: 'SELECT 1' }],+ ],])('says why there is nothing to open when %s', async (_case, runs) => {;(dataQualityChecksRunsList as jest.Mock).mockResolvedValue(runs)await mountLogic()diff --git a/products/data_quality/frontend/suiteRuns.ts b/products/data_quality/frontend/suiteRuns.tsindex e7c5d88fe49a..95c8057851c5 100644--- a/products/data_quality/frontend/suiteRuns.ts+++ b/products/data_quality/frontend/suiteRuns.ts@@ -20,8 +20,8 @@ export function pollDelayMs(elapsedMs: number): number {}/** The newest run that still has its query. Retention clears the compiled query after 30 days. */-export function latestFailingRowsQuery(runs: DataQualityCheckRunApi[]): string | null {- return runs.find((run) => run.compiled_query)?.compiled_query || null+export function latestRunWithQuery(runs: DataQualityCheckRunApi[]): DataQualityCheckRunApi | null {+ return runs.find((run) => run.compiled_query || run.audited_staged_refresh) ?? null}export type SuiteRunOutcome = 'empty' | 'errored' | 'warning' | 'success'diff --git a/products/data_quality/skills/authoring-data-quality-checks/SKILL.md b/products/data_quality/skills/authoring-data-quality-checks/SKILL.mdindex bb821e3566f2..4684e1d1d9e1 100644--- a/products/data_quality/skills/authoring-data-quality-checks/SKILL.md+++ b/products/data_quality/skills/authoring-data-quality-checks/SKILL.md@@ -164,7 +164,7 @@ assertion is wrong. Take the `compiled_query` off the run, execute it with `postlook at what it actually matched before reporting anything. That `compiled_query` comes from`posthog:data-quality-check-results`; the information_schema poll in step 3 does not return it. An `errored` result is never a dataproblem — the query could not run at all, usually a column name typo or a subject that no longer-exists.+exists. To dig further into a failed or errored run, use `debugging-failed-data-quality-checks`.## Judging a source before you use it@@ -190,3 +190,4 @@ Tests tab to inspect the current rows that violate the check.- `setting-up-data-catalog` — what the data _means_: metrics, trust marks, relationships.- `querying-posthog-data` — the schema-discovery and HogQL rules these queries follow.+- `debugging-failed-data-quality-checks` — why a check failed or errored, and a refresh the gate did not publish.diff --git a/products/data_quality/skills/debugging-failed-data-quality-checks/SKILL.md b/products/data_quality/skills/debugging-failed-data-quality-checks/SKILL.mdnew file mode 100644index 000000000000..33ab29a714bd--- /dev/null+++ b/products/data_quality/skills/debugging-failed-data-quality-checks/SKILL.md@@ -0,0 +1,130 @@+---+name: debugging-failed-data-quality-checks+description: >+ Finds out why a data quality check failed or errored, looks at the rows it matched, and recommends+ the fix. Also covers a materialized view refresh that the data quality gate did not publish. Use+ when asked why a check is red, what rows failed, why a view shows "Not published", why a view's+ data is stale after a refresh, or how to get a blocked refresh published. Trigger terms: failed+ check, failing rows, errored check, data quality failure, not published, blocked materialization,+ unpublished refresh, check keeps failing.+---++# Debugging failed data quality checks++A check run ends in one of four states.+Read the state first, because it decides where the problem is:++| Status | Meaning | Where to look |+| --------- | ---------------------------------------------- | -------------------------------------- |+| `failed` | The query ran and the assertion found bad data | The data, or the assertion itself |+| `errored` | The query could not run, so nothing was judged | The error text (never a data problem) |+| `skipped` | The subject is gone | Whether the table or view still exists |+| `passed` | The assertion held | Nothing |++`row_count` and `freshness` checks judge `observed_value`, not `failed_row_count`.+A failed `row_count` means the count fell outside its bounds.+A failed `freshness` means the newest row is older than the limit.++## When to use this skill++- A check or a subject shows `failed` or `errored` and the user wants to know why+- The user wants to see the rows a check matched+- A materialized view's latest run shows an error that starts with `Not published:`+- A view kept serving old data after a refresh, and the data quality gate is on+- Another skill (`authoring-data-quality-checks` or `auditing-warehouse-view-health`) found a failing check or a blocked view and handed it off++## Available tools++| Tool | Purpose |+| ------------------------------------ | --------------------------------------------------------------------------- |+| `posthog:data-quality-check-results` | A check's recent runs, with `compiled_query`, `error` and the config it ran |+| `posthog:execute-sql` | Re-run a run's `compiled_query` to see the failing rows |+| `posthog:data-quality-check-run` | Run a check now |+| `posthog:data-quality-check-update` | Fix an assertion or change its severity |+| `view-get` | A view's definition and status |+| `view-run-history` | A view's materialization runs and their errors |+| `view-run` | Materialize a view again |++To find the failing checks, query `system.information_schema.data_quality_checks` for `last_status IN ('failed', 'errored')`, or `system.information_schema.data_quality_health` for a subject's verdict.++## Workflow++### Step 1: Read the run++Call `posthog:data-quality-check-results` for the check.+On the newest run, read:++- `status` and `error`+- `check_config` and `check_severity`: what the run asserted, which can differ from the check today+- `compiled_query`: HogQL that selects the failing rows. For `row_count` it returns the count instead, so judge that check by `observed_value`.+- `audited_staged_refresh`: true when the run was part of a gated audit of a refresh before it was published. An errored run can carry it too, so read `status` first.++Retention clears `compiled_query` after 30 days.+For an older run, run the check again.++### Step 2: Look at the failing rows++Run `compiled_query` with `posthog:execute-sql`.+An empty `compiled_query` means there is nothing to replay: retention cleared it, or a gated run could not read the view's definition.+Look at what it matched before you report anything.+A failure means one of two things: the data is bad, or the assertion is wrong.+The rows tell you which.++When `audited_staged_refresh` is true, the query does not read the published table.+It holds the view's definition in a `WITH` clause and reads the view's source tables now.+The sources may have changed since the run, so the rows and the count can differ from the run.+A query that now returns zero rows does not prove that the refresh was clean.+Compare with `failed_row_count` on the run.++### Step 3: Read an errored run++An errored run did not judge the data.+Match the error text:++| Error text | Cause and fix |+| ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `The staged files could not be read, so this data was not audited.` | The gate could not reach the refresh before publish. The refresh publishes without a verdict. Run the view again. |+| `Metric checks cannot audit staged data.` | A metric check was part of a gated refresh. It runs on its own schedule instead. |+| `The check query returned no rows.` | The aggregate query returned nothing. Run the check again and report it if it repeats. |+| `A check that reads another subject needs an initiator or author…` | An automatic run of a `custom_sql` or `relationships` check has no user to run as. A manual run works. An edit to the check's assertion makes the editor its author. |+| A HogQL or ClickHouse error | A column name typo, a type mismatch, or a query that ran out of time. Fix the config, or add `lookback_hours`. |++Two messages come with `skipped`: `The subject was deleted.` and `The subject no longer resolves.`+The table or view is gone.+Delete the check or point it at the replacement.++### Step 4: Understand a blocked refresh++When the team turns on "Block materialization on failing checks", a materialized view's error-severity checks run on each refresh before it is published.+If one fails:++- The view's run shows an error that starts with `Not published:` (see `view-run-history`).+- The previous version of the view keeps serving queries.+- Downstream views in the same DAG are skipped for this run.+- The view's schedule is not paused.+ The next scheduled refresh runs the checks again.++Warn-severity checks never block a refresh.++### Step 5: Recover++Fix the cause, then prove it:++1. Fix the upstream data, or fix the assertion with `posthog:data-quality-check-update`.+ If the failure is real but must not block the refresh, change `severity` to `warn`.+2. For a blocked view, call `view-run` to materialize it again.+ Otherwise call `posthog:data-quality-check-run`.+3. Read `posthog:data-quality-check-results` again and confirm the newest run passed.++## Important notes++- Do not change a check's severity or assertion only to turn it green.+ Confirm with the user first.+- `errored` is never evidence of bad data, and `passed` on an empty table is not evidence of good data.+- A check reports against its subject, but a `custom_sql` query can read other tables.+ Read the query before you blame the subject.++## Related++- `authoring-data-quality-checks`: writing and choosing checks+- `auditing-warehouse-view-health`: finding failing materialized viewsdiff --git a/products/data_warehouse/skills/auditing-warehouse-view-health/SKILL.md b/products/data_warehouse/skills/auditing-warehouse-view-health/SKILL.mdindex 37b1c4891cd5..2c890b250059 100644--- a/products/data_warehouse/skills/auditing-warehouse-view-health/SKILL.md+++ b/products/data_warehouse/skills/auditing-warehouse-view-health/SKILL.md@@ -72,6 +72,9 @@ Materialized view failures are usually independent of sources — a view failureitself (syntax error, missing table reference, type mismatch). For each failing view, surface the `error` and pointat the offending query. Use `view-run-history` if the user wants the failure trail.+An `error` that starts with `Not published:` is not a query problem. The view's data quality checks failed and the+refresh was held back. Hand off to `debugging-failed-data-quality-checks`.+### Step 3 — Present the auditRender a prioritized report. Don't dump the raw JSON — human-readable:diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a13482dd2f4b..1e3d2c1de0a8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27741,8 +27741,10 @@ export namespace Schemas {* @nullable*/readonly observed_value: number | null;- /** The HogQL that ran. Re-run it to see the offending rows. */+ /** HogQL selecting the failing rows. Re-run it to see them. For a run that audited a staged refresh it inlines the view's definition, so it reads the source tables rather than the published table. Empty when there is nothing to replay: retention cleared it, or a staged run could not build its replay query. */readonly compiled_query: string;+ /** True when the run audited a refresh that was staged but not yet published, under the materialization gate. */+ readonly audited_staged_refresh: boolean;/** Compilation or execution failure, when status is 'errored'. */readonly error: string;/** @nullable */