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.

feat(data-quality): gate materialization on staged data quality checks (#79114)

Thiago Salvatoreb51817a9f575
diff --git a/posthog/temporal/data_modeling/__init__.py b/posthog/temporal/data_modeling/__init__.py
index 5cd3e7cda0e4..f0859c7cffb6 100644
--- a/posthog/temporal/data_modeling/__init__.py
+++ b/posthog/temporal/data_modeling/__init__.py
@@ -9,7 +9,10 @@ from posthog.temporal.data_modeling.activities import (
notify_dag_materialization_failures_activity,
preempt_dag_run_activity,
prepare_queryable_table_activity,
+ publish_queryable_table_activity,
+ quality_block_materialization_activity,
record_skipped_data_modeling_jobs_activity,
+ stage_queryable_files_activity,
succeed_materialization_activity,
)
from posthog.temporal.data_modeling.run_workflow import (
@@ -45,6 +48,9 @@ ACTIVITIES = [
materialize_view_activity,
materialize_view_duckgres_activity,
prepare_queryable_table_activity,
+ publish_queryable_table_activity,
+ quality_block_materialization_activity,
+ stage_queryable_files_activity,
succeed_materialization_activity,
finish_run_activity,
start_run_activity,
diff --git a/posthog/temporal/data_modeling/activities/__init__.py b/posthog/temporal/data_modeling/activities/__init__.py
index 29d1807f13aa..3294b3a12dcd 100644
--- a/posthog/temporal/data_modeling/activities/__init__.py
+++ b/posthog/temporal/data_modeling/activities/__init__.py
@@ -24,8 +24,13 @@ from .preempt_dag_run import PreemptDAGRunInputs, preempt_dag_run_activity
from .prepare_queryable_table import (
PrepareQueryableTableInputs,
PrepareQueryableTableResult,
+ PublishQueryableTableInputs,
+ StageQueryableFilesResult,
prepare_queryable_table_activity,
+ publish_queryable_table_activity,
+ stage_queryable_files_activity,
)
+from .quality_block_materialization import QualityBlockMaterializationInputs, quality_block_materialization_activity
from .succeed_materialization import (
SucceedMaterializationInputs,
SucceedMaterializationResult,
@@ -48,6 +53,9 @@ __all__ = [
"PreemptDAGRunInputs",
"PrepareQueryableTableInputs",
"PrepareQueryableTableResult",
+ "PublishQueryableTableInputs",
+ "QualityBlockMaterializationInputs",
+ "StageQueryableFilesResult",
"SucceedMaterializationInputs",
"SucceedMaterializationResult",
"check_duckgres_shadow_enabled_activity",
@@ -61,5 +69,8 @@ __all__ = [
"get_dag_structure_activity",
"preempt_dag_run_activity",
"prepare_queryable_table_activity",
+ "publish_queryable_table_activity",
+ "quality_block_materialization_activity",
+ "stage_queryable_files_activity",
"succeed_materialization_activity",
]
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index 9d78ef376e2b..e2b679513f41 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -55,6 +55,8 @@ from products.data_modeling.backend.facade.api import (
)
from products.data_modeling.backend.facade.modeling import bounded_resolver_factory_for_view
from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery, Node, NodeType
+from products.data_quality.backend.facade import api as data_quality_facade
+from products.data_quality.backend.facade.contracts import QUALITY_AUDIT_SKIP, QualityAuditMode
from products.data_warehouse.backend.facade.api import ensure_bucket_exists, get_s3_client
from products.endpoints.backend.facade.temporal import prepare_executable_query
@@ -177,7 +179,7 @@ class MaterializeViewInputs:
}
[email protected](frozen=False)
class MaterializeViewResult:
node_id: str
node_name: str
@@ -185,6 +187,7 @@ class MaterializeViewResult:
table_uri: str
file_uris: list[str]
saved_query_id: str
+ quality_audit: QualityAuditMode = QUALITY_AUDIT_SKIP
# Whether this run upserted a window rather than rebuilding. Defaulted so old workflow
# histories decode without it.
incremental: bool = False
@@ -839,6 +842,9 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
)
await logger.ainfo(f"Materialized node {objects.node.name} with {row_count} rows")
+ quality_audit = await database_sync_to_async_pool(data_quality_facade.quality_audit_mode)(
+ inputs.team_id, str(objects.saved_query.id)
+ )
return MaterializeViewResult(
node_id=objects.node.id,
node_name=objects.node.name,
@@ -846,5 +852,6 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
table_uri=table_uri,
file_uris=file_uris,
saved_query_id=str(objects.saved_query.id),
+ quality_audit=quality_audit,
incremental=plan.incremental,
)
diff --git a/posthog/temporal/data_modeling/activities/prepare_queryable_table.py b/posthog/temporal/data_modeling/activities/prepare_queryable_table.py
index 1f7b064e0ffd..a64e8d89d16f 100644
--- a/posthog/temporal/data_modeling/activities/prepare_queryable_table.py
+++ b/posthog/temporal/data_modeling/activities/prepare_queryable_table.py
@@ -63,22 +63,24 @@ class PrepareQueryableTableResult:
total_storage_mib: float | None
-async def prepare_queryable_table_activity(inputs: PrepareQueryableTableInputs) -> PrepareQueryableTableResult:
- """Prepare materialized files for querying and create DataWarehouseTable.
[email protected](frozen=False)
+class StageQueryableFilesResult:
+ staged_folder_path: str
- Returns storage metrics (delta and total MiB) for the materialized table.
- """
- bind_data_modeling_log_context(inputs.team_id, inputs.saved_query_id)
- logger = LOGGER.bind()
- saved_query = await _get_saved_query_with_table(inputs)
[email protected](frozen=False)
+class PublishQueryableTableInputs(PrepareQueryableTableInputs):
+ # Keyword-only so it can stay required behind the defaulted fields it inherits.
+ staged_folder_path: str = dataclasses.field(kw_only=True)
+
+
+async def _stage_files(inputs: PrepareQueryableTableInputs, saved_query: DataWarehouseSavedQuery, logger) -> str:
queryable_folder = saved_query.table.queryable_folder if saved_query.table else None
await logger.adebug(
f"Copying query files to S3: folder_path={saved_query.folder_path} table_name={saved_query.normalized_name} "
f"existing_queryable_folder={queryable_folder}"
)
- folder_path = await prepare_s3_files_for_querying(
+ return await prepare_s3_files_for_querying(
folder_path=saved_query.folder_path,
table_name=saved_query.normalized_name,
file_uris=inputs.file_uris,
@@ -86,6 +88,14 @@ async def prepare_queryable_table_activity(inputs: PrepareQueryableTableInputs)
existing_queryable_folder=queryable_folder,
logger=logger,
)
+
+
+async def _publish_table(
+ inputs: PrepareQueryableTableInputs,
+ saved_query: DataWarehouseSavedQuery,
+ folder_path: str,
+ logger,
+) -> PrepareQueryableTableResult:
await logger.ainfo("Preparing table for querying")
create_result = await create_table_from_saved_query(
inputs.job_id, inputs.saved_query_id, inputs.team_id, folder_path
@@ -98,3 +108,38 @@ async def prepare_queryable_table_activity(inputs: PrepareQueryableTableInputs)
storage_delta_mib=create_result.storage_delta_mib,
total_storage_mib=create_result.total_storage_mib,
)
+
+
+async def prepare_queryable_table_activity(inputs: PrepareQueryableTableInputs) -> PrepareQueryableTableResult:
+ """Prepare materialized files for querying and create DataWarehouseTable.
+
+ Returns storage metrics (delta and total MiB) for the materialized table.
+ """
+ bind_data_modeling_log_context(inputs.team_id, inputs.saved_query_id)
+ logger = LOGGER.bind()
+
+ saved_query = await _get_saved_query_with_table(inputs)
+ folder_path = await _stage_files(inputs, saved_query, logger)
+ return await _publish_table(inputs, saved_query, folder_path, logger)
+
+
+async def stage_queryable_files_activity(inputs: PrepareQueryableTableInputs) -> StageQueryableFilesResult:
+ """Copy files into a new queryable folder, leaving the table pointed at the previous one."""
+ bind_data_modeling_log_context(inputs.team_id, inputs.saved_query_id)
+ logger = LOGGER.bind()
+
+ saved_query = await _get_saved_query_with_table(inputs)
+ folder_path = await _stage_files(inputs, saved_query, logger)
+ return StageQueryableFilesResult(staged_folder_path=folder_path)
+
+
+async def publish_queryable_table_activity(inputs: PublishQueryableTableInputs) -> PrepareQueryableTableResult:
+ """Repoint the table at a folder stage_queryable_files_activity already wrote."""
+ bind_data_modeling_log_context(inputs.team_id, inputs.saved_query_id)
+ logger = LOGGER.bind()
+
+ saved_query = await _get_saved_query_with_table(inputs)
+ return await _publish_table(inputs, saved_query, inputs.staged_folder_path, logger)
diff --git a/posthog/temporal/data_modeling/activities/quality_block_materialization.py b/posthog/temporal/data_modeling/activities/quality_block_materialization.py
new file mode 100644
index 000000000000..72927999a644
--- /dev/null
+++ b/posthog/temporal/data_modeling/activities/quality_block_materialization.py
@@ -0,0 +1,80 @@
+import datetime as dt
+import dataclasses
+
+from django.db import transaction
+
+from structlog import get_logger
+from structlog.contextvars import bind_contextvars
+from temporalio import activity
+
+from posthog.sync import database_sync_to_async_pool
+
+from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobStatus, Node
+
+from .utils import QUALITY_BLOCKED_ERROR_PREFIX, update_node_system_properties
+
+LOGGER = get_logger(__name__)
+
+
[email protected](frozen=False)
+class QualityBlockMaterializationInputs:
+ team_id: int
+ node_id: str
+ dag_id: str
+ job_id: str
+ blocking_failures: int
+ suite_run_id: str | None = None
+
+ @property
+ def properties_to_log(self) -> dict:
+ return {
+ "team_id": self.team_id,
+ "node_id": self.node_id,
+ "dag_id": self.dag_id,
+ "job_id": self.job_id,
+ "blocking_failures": self.blocking_failures,
+ }
+
+
+def _quality_error(inputs: QualityBlockMaterializationInputs) -> str:
+ checks = "check" if inputs.blocking_failures == 1 else "checks"
+ return (
+ f"{QUALITY_BLOCKED_ERROR_PREFIX} {inputs.blocking_failures} data quality {checks} failed. "
+ "The previous version keeps serving until the checks pass."
+ )
+
+
+@database_sync_to_async_pool
+def _block_node_and_job(inputs: QualityBlockMaterializationInputs) -> None:
+ error = _quality_error(inputs)
+ with transaction.atomic():
+ node = Node.objects.select_for_update().get(id=inputs.node_id, team_id=inputs.team_id, dag_id=inputs.dag_id)
+ update_node_system_properties(
+ node,
+ status=DataModelingJobStatus.FAILED,
+ job_id=inputs.job_id,
+ error=error,
+ )
+ node.save()
+
+ job = DataModelingJob.objects.get(id=inputs.job_id)
+ if job.status in (DataModelingJobStatus.FAILED, DataModelingJobStatus.CANCELLED, DataModelingJobStatus.COMPLETED):
+ return
+ job.status = DataModelingJobStatus.FAILED
+ job.error = error
+ job.last_run_at = dt.datetime.now(dt.UTC)
+ job.save()
+
+
+async def quality_block_materialization_activity(inputs: QualityBlockMaterializationInputs) -> None:
+ """Deliberately not ``fail_materialization_activity``: bad upstream data must not pause this
+ node's schedule, revert it, or count toward suspending it.
+ """
+ bind_contextvars(team_id=inputs.team_id)
+ logger = LOGGER.bind()
+ await _block_node_and_job(inputs)
+ await logger.ainfo(
+ "Materialization blocked by data quality checks",
+ **inputs.properties_to_log,
+ )
diff --git a/posthog/temporal/data_modeling/activities/utils.py b/posthog/temporal/data_modeling/activities/utils.py
index 074d01bf98c9..51222abb029c 100644
--- a/posthog/temporal/data_modeling/activities/utils.py
+++ b/posthog/temporal/data_modeling/activities/utils.py
@@ -57,6 +57,9 @@ CONSECUTIVE_FAILURES_TO_SUSPEND = 5
SUSPENSION_ENFORCEMENT_FLAG = "data-modeling-suspend-failing-nodes"
+# Shared with quality_block_materialization so the counter below can recognize its job rows.
+QUALITY_BLOCKED_ERROR_PREFIX = "Not published:"
+
def get_previous_jobs(
saved_query_id: UUID, current_job: DataModelingJob, count: int, ignore_inconclusive: bool = False
@@ -101,6 +104,8 @@ EXTERNALLY_ABORTED_MARKERS = (
"QueueEmpty: ", # no root node to start from, so the graph was refused rather than the query
"Preempted: ",
ABANDONED_ERROR,
+ # the query ran and produced rows; only the publish was refused
+ QUALITY_BLOCKED_ERROR_PREFIX,
)
diff --git a/posthog/temporal/data_modeling/workflows/execute_dag.py b/posthog/temporal/data_modeling/workflows/execute_dag.py
index 58c964c6247b..1d1e2e82f997 100644
--- a/posthog/temporal/data_modeling/workflows/execute_dag.py
+++ b/posthog/temporal/data_modeling/workflows/execute_dag.py
@@ -41,6 +41,8 @@ from products.data_quality.backend.facade.enums import SuiteRunTrigger
MAX_CONCURRENT_CHILDREN = 10
+NODE_AUDIT_PATCH = "data-quality-node-audit-2026-08"
+
class EmptyDAGOrCycleError(Exception):
"""Raised when the DAG is empty or contains a cycle according to _dag_execution_levels."""
@@ -74,7 +76,7 @@ class ExecuteDAGInputs:
}
[email protected](frozen=False)
class NodeResult:
"""Result for a single node materialization."""
@@ -85,6 +87,8 @@ class NodeResult:
error: str | None = None
skipped: bool = False
skip_reason: str | None = None
+ quality_failed: bool = False
+ quality_audited: bool = False
@dataclasses.dataclass
@@ -276,6 +280,7 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
node_results: list[NodeResult] = []
ephemeral_node_set = set(dag_structure.ephemeral_nodes)
failed_node_set: set[str] = set()
+ quality_failed_node_set: set[str] = set()
serving_engine = (
DataModelingJobEngine.DUCKGRES if inputs.duckgres_only else DataModelingJobEngine.CLICKHOUSE
).value
@@ -314,7 +319,13 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
(suspended_upstream if suspended else failed_upstream).append(blocked_id)
if not should_skip:
should_skip = True
- skip_reason = f"Upstream node {blocked_id} {'suspended' if suspended else 'failed'}"
+ if suspended:
+ verb = "suspended"
+ elif blocked_id in quality_failed_node_set:
+ verb = "failed data quality checks"
+ else:
+ verb = "failed"
+ skip_reason = f"Upstream node {blocked_id} {verb}"
if should_skip:
skip_nodes.append((node_id, skip_reason))
if node_id not in ephemeral_node_set and (failed_upstream or suspended_upstream):
@@ -375,6 +386,19 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
)
try:
result: MaterializeViewWorkflowResult = await handle
+ if result.quality_blocking_failures is not None and result.quality_blocking_failures > 0:
+ temporalio.workflow.logger.warning(
+ f"Node {node_id} materialized but was not published: "
+ f"{result.quality_blocking_failures} data quality checks failed",
+ extra=inputs.properties_to_log,
+ )
+ return NodeResult(
+ node_id=node_id,
+ success=False,
+ error=f"Not published: {result.quality_blocking_failures} data quality checks failed",
+ quality_failed=True,
+ quality_audited=True,
+ )
temporalio.workflow.logger.info(
f"Node {node_id} materialized successfully",
extra={"rows_materialized": result.rows_materialized, **inputs.properties_to_log},
@@ -384,6 +408,7 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
success=True,
rows_materialized=result.rows_materialized,
duration_seconds=result.duration_seconds,
+ quality_audited=result.quality_audited,
)
except temporalio.exceptions.ChildWorkflowError as e:
error_message = str(e.cause) if e.cause else str(e)
@@ -414,6 +439,8 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
node_results.append(nr)
if not nr.success:
failed_node_set.add(nr.node_id)
+ if nr.quality_failed:
+ quality_failed_node_set.add(nr.node_id)
if skipped_jobs:
await temporalio.workflow.execute_activity(
@@ -488,17 +515,27 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
)
async def _run_data_quality_checks(self, inputs: ExecuteDAGInputs, node_results: list[NodeResult]) -> None:
- """Fire the check suite for the models this run brought up to date.
+ """Fire the check suite for the nodes this run refreshed but did not audit per-node.
Best-effort and fully isolated: started by registered name so data_modeling never imports
the catalog product, and ABANDON so a check suite can neither delay nor fail the DAG. The
- node ids come from recorded activity results, so replay stays deterministic.
+ node ids come from recorded child results, so replay stays deterministic.
The gate activity owns the feature flag and the "are there any checks here" question, both
of which need the database. Asking first keeps a team with no checks, or an org that never
opted in, from paying for a child workflow and a suite row on every materialization.
"""
- checkable_node_ids = [result.node_id for result in node_results if result.success and not result.skipped]
+ # Filtering can empty the list and skip the commands below, so an old history that recorded
+ # them has to keep taking the old path. A rolling deploy reaches this: an old worker can
+ # record those commands against a new child's quality_audited result.
+ if temporalio.workflow.patched(NODE_AUDIT_PATCH):
+ checkable_node_ids = [
+ result.node_id
+ for result in node_results
+ if result.success and not result.skipped and not result.quality_audited
+ ]
+ else:
+ checkable_node_ids = [result.node_id for result in node_results if result.success and not result.skipped]
if not checkable_node_ids:
return
diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.py
index 58f3ddad30cc..dba3f2071cce 100644
--- a/posthog/temporal/data_modeling/workflows/materialize_view.py
+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py
@@ -1,4 +1,5 @@
import json
+import asyncio
import datetime as dt
import dataclasses
@@ -17,7 +18,12 @@ from posthog.temporal.data_modeling.activities import (
DuckgresShadowResult,
FailMaterializationInputs,
MaterializeViewInputs,
+ MaterializeViewResult,
PrepareQueryableTableInputs,
+ PrepareQueryableTableResult,
+ PublishQueryableTableInputs,
+ QualityBlockMaterializationInputs,
+ StageQueryableFilesResult,
SucceedMaterializationInputs,
SucceedMaterializationResult,
check_duckgres_shadow_enabled_activity,
@@ -26,6 +32,9 @@ from posthog.temporal.data_modeling.activities import (
materialize_view_activity,
materialize_view_duckgres_activity,
prepare_queryable_table_activity,
+ publish_queryable_table_activity,
+ quality_block_materialization_activity,
+ stage_queryable_files_activity,
succeed_materialization_activity,
)
from posthog.temporal.data_modeling.activities.enrich_view_semantics import EnrichViewSemanticsInputs
@@ -46,6 +55,19 @@ from posthog.temporal.data_modeling.metrics import (
from posthog.temporal.data_modeling.workflows.enrich_view_semantics import EnrichViewSemanticsWorkflow
from products.data_modeling.backend.facade.models import DataModelingJobEngine
+from products.data_quality.backend.facade.contracts import (
+ CHECK_SUITE_WORKFLOW_NAME,
+ QUALITY_AUDIT_GATE,
+ QUALITY_AUDIT_SKIP,
+ QUALITY_AUDIT_WARN,
+ QualityAuditMode,
+ is_quality_audit_mode,
+)
+from products.data_quality.backend.facade.enums import SuiteRunTrigger
+
+# Covers every command the data quality feature adds here: the stage/audit/publish trio and the
+# warn-mode suite child.
+QUALITY_AUDIT_PATCH = "data-quality-audit-2026-08"
# these indicate problems with the query or data, not transient issues
NON_RETRYABLE_ERRORS = [
@@ -57,6 +79,15 @@ NON_RETRYABLE_ERRORS = [
]
+def _is_cancellation(error: BaseException) -> bool:
+ """The SDK never re-delivers a cancel, so a handler that swallows one keeps issuing commands."""
+ if isinstance(error, temporalio.exceptions.CancelledError | asyncio.CancelledError):
+ return True
+ return isinstance(
+ error, temporalio.exceptions.ActivityError | temporalio.exceptions.ChildWorkflowError
+ ) and isinstance(error.cause, temporalio.exceptions.CancelledError)
+
+
@dataclasses.dataclass
class MaterializeViewWorkflowInputs:
"""Inputs for the MaterializeViewWorkflow.
@@ -82,7 +113,7 @@ class MaterializeViewWorkflowInputs:
}
[email protected](frozen=False)
class MaterializeViewWorkflowResult:
"""Result from the MaterializeViewWorkflow.
@@ -91,12 +122,18 @@ class MaterializeViewWorkflowResult:
node_id: The ID of the node that was materialized.
rows_materialized: The number of rows written to the delta table.
duration_seconds: The total duration of the workflow in seconds.
+ quality_blocking_failures: Error-severity check failures that blocked the publish. None
+ means no gated audit ran.
+ quality_audited: Whether a check suite covered this run, so the DAG's post-run sweep must
+ not run one again.
"""
job_id: str
node_id: str
rows_materialized: int
duration_seconds: float
+ quality_blocking_failures: int | None = None
+ quality_audited: bool = False
@temporalio.workflow.defn(name="data-modeling-materialize-view")
@@ -212,22 +249,85 @@ class MaterializeViewWorkflow(PostHogWorkflow):
# materialize_view_activity guarantees file_uris is non-empty even for
# zero-row results — it falls back to _write_empty_parquet_for_zero_rows
# so prepare_s3_files_for_querying has something to list.
- storage_result = await temporalio.workflow.execute_activity(
- prepare_queryable_table_activity,
- PrepareQueryableTableInputs(
- team_id=inputs.team_id,
- job_id=job_id,
- saved_query_id=materialize_result.saved_query_id,
- table_uri=materialize_result.table_uri,
- file_uris=materialize_result.file_uris,
- row_count=materialize_result.row_count,
- incremental=materialize_result.incremental,
- ),
- start_to_close_timeout=dt.timedelta(minutes=5),
- retry_policy=temporalio.common.RetryPolicy(
- maximum_attempts=3,
- ),
+ # Reading the mode as skip when the marker is absent keeps every command this
+ # feature adds out of a history that predates it. A rolling deploy can hand an old
+ # workflow worker a result from new activity code, and the SDK drops the fields the
+ # old dataclass lacks, so the mode alone cannot say who wrote the history.
+ quality_audit = (
+ self._audit_mode(materialize_result, inputs)
+ if temporalio.workflow.patched(QUALITY_AUDIT_PATCH)
+ else QUALITY_AUDIT_SKIP
+ )
+ staged_verdict: int | None = None
+ prepare_inputs = PrepareQueryableTableInputs(
+ team_id=inputs.team_id,
+ job_id=job_id,
+ saved_query_id=materialize_result.saved_query_id,
+ table_uri=materialize_result.table_uri,
+ file_uris=materialize_result.file_uris,
+ row_count=materialize_result.row_count,
+ incremental=materialize_result.incremental,
)
+ if quality_audit == QUALITY_AUDIT_GATE:
+ stage_result: StageQueryableFilesResult = await temporalio.workflow.execute_activity(
+ stage_queryable_files_activity,
+ prepare_inputs,
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),
+ )
+ staged_verdict = await self._staged_audit_verdict(
+ inputs, job_id, materialize_result, stage_result.staged_folder_path
+ )
+ if staged_verdict:
+ await temporalio.workflow.execute_activity(
+ quality_block_materialization_activity,
+ QualityBlockMaterializationInputs(
+ team_id=inputs.team_id,
+ node_id=inputs.node_id,
+ dag_id=inputs.dag_id,
+ job_id=job_id,
+ blocking_failures=staged_verdict,
+ ),
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),
+ )
+ get_node_finished_metric("quality_blocked").add(1)
+ end_time = temporalio.workflow.now()
+ blocked_duration_seconds = (end_time - start_time).total_seconds()
+ if duckgres_shadow_handle is not None:
+ await self._collect_shadow_comparison(
+ duckgres_shadow_handle,
+ duckgres_job_id,
+ materialize_result.row_count,
+ blocked_duration_seconds,
+ inputs,
+ )
+ return MaterializeViewWorkflowResult(
+ job_id=job_id,
+ node_id=inputs.node_id,
+ rows_materialized=materialize_result.row_count,
+ duration_seconds=blocked_duration_seconds,
+ quality_blocking_failures=staged_verdict,
+ quality_audited=True,
+ )
+ storage_result: PrepareQueryableTableResult = await temporalio.workflow.execute_activity(
+ publish_queryable_table_activity,
+ PublishQueryableTableInputs(
+ **dataclasses.asdict(prepare_inputs),
+ staged_folder_path=stage_result.staged_folder_path,
+ ),
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),
+ )
+ else:
+ storage_result = await temporalio.workflow.execute_activity(
+ prepare_queryable_table_activity,
+ prepare_inputs,
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=temporalio.common.RetryPolicy(
+ maximum_attempts=3,
+ ),
+ )
# handle success
end_time = temporalio.workflow.now()
duration_seconds = (end_time - start_time).total_seconds()
@@ -253,6 +353,10 @@ class MaterializeViewWorkflow(PostHogWorkflow):
# None for in-flight runs on the pre-deploy activity version — treat that as "not needed".
await self._maybe_enrich_view_semantics(inputs, succeed_result)
+ quality_audited = staged_verdict is not None
+ if quality_audit == QUALITY_AUDIT_WARN:
+ quality_audited = await self._start_suite_on_published_data(inputs, job_id, materialize_result)
+
# after the main workflow succeeds, collect shadow stats for comparison
if duckgres_shadow_handle is not None:
await self._collect_shadow_comparison(
@@ -286,12 +390,12 @@ class MaterializeViewWorkflow(PostHogWorkflow):
node_id=inputs.node_id,
rows_materialized=materialize_result.row_count,
duration_seconds=duration_seconds,
+ quality_blocking_failures=staged_verdict,
+ quality_audited=quality_audited,
)
except Exception as e:
# handle failure
- cancelled = isinstance(e, temporalio.exceptions.ActivityError) and isinstance(
- e.cause, temporalio.exceptions.CancelledError
- )
+ cancelled = _is_cancellation(e)
if cancelled:
error_message = "Workflow was cancelled"
elif isinstance(e, temporalio.exceptions.ActivityError):
@@ -352,6 +456,96 @@ class MaterializeViewWorkflow(PostHogWorkflow):
duration_seconds=result.duration_seconds if result else 0,
)
+ async def _staged_audit_verdict(
+ self,
+ inputs: MaterializeViewWorkflowInputs,
+ job_id: str,
+ materialize_result: MaterializeViewResult,
+ staged_folder_path: str,
+ ) -> int | None:
+ """The blocking-failure count, or None when the audit reached no verdict.
+
+ None still publishes, because a broken check pipeline is not a verdict on the data, and it
+ leaves the node to the DAG's sweep so the checks get another chance. Cancellation is not
+ such a case, so it propagates rather than publishing unaudited data.
+ """
+ try:
+ result = await temporalio.workflow.execute_child_workflow(
+ CHECK_SUITE_WORKFLOW_NAME,
+ {
+ "team_id": inputs.team_id,
+ "trigger": SuiteRunTrigger.MATERIALIZATION.value,
+ "saved_query_ids": [materialize_result.saved_query_id],
+ "data_modeling_job_id": job_id,
+ "staged_queryable_folder": staged_folder_path,
+ },
+ id=f"data-quality-gate-{job_id}",
+ task_queue=settings.DATA_MODELING_TASK_QUEUE,
+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1),
+ execution_timeout=dt.timedelta(minutes=30),
+ )
+ except Exception as e:
+ if _is_cancellation(e):
+ raise
+ capture_exception(e)
+ temporalio.workflow.logger.warning(
+ "Staged data quality audit did not complete; publishing without a verdict",
+ extra={"error": str(e), **inputs.properties_to_log},
+ )
+ return None
+ if isinstance(result, dict):
+ return int(result.get("checks_failed_blocking") or 0)
+ return None
+
+ async def _start_suite_on_published_data(
+ self,
+ inputs: MaterializeViewWorkflowInputs,
+ job_id: str,
+ materialize_result: MaterializeViewResult,
+ ) -> bool:
+ """False sends the node back to the DAG's sweep, which is where a failed start gets covered."""
+ try:
+ await temporalio.workflow.start_child_workflow(
+ CHECK_SUITE_WORKFLOW_NAME,
+ {
+ "team_id": inputs.team_id,
+ "trigger": SuiteRunTrigger.MATERIALIZATION.value,
+ "saved_query_ids": [materialize_result.saved_query_id],
+ "data_modeling_job_id": job_id,
+ },
+ id=f"data-quality-materialization-{job_id}",
+ parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,
+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1),
+ execution_timeout=dt.timedelta(hours=1),
+ )
+ except WorkflowAlreadyStartedError:
+ temporalio.workflow.logger.info(
+ "Data quality checks already running for this job, skipping",
+ extra=inputs.properties_to_log,
+ )
+ return True
+ except Exception as e:
+ capture_exception(e)
+ temporalio.workflow.logger.warning(
+ "Could not start the data quality check suite",
+ extra={"error": str(e), **inputs.properties_to_log},
+ )
+ return False
+ return True
+
+ def _audit_mode(
+ self, materialize_result: MaterializeViewResult, inputs: MaterializeViewWorkflowInputs
+ ) -> QualityAuditMode:
+ """A mode this version does not know reads as ``skip``, the behavior that predates the gate."""
+ mode = materialize_result.quality_audit
+ if is_quality_audit_mode(mode):
+ return mode
+ temporalio.workflow.logger.warning(
+ f"Unknown data quality audit mode {mode!r}, publishing without a gate",
+ extra=inputs.properties_to_log,
+ )
+ return QUALITY_AUDIT_SKIP
+
async def _maybe_enrich_view_semantics(
self,
inputs: MaterializeViewWorkflowInputs,
diff --git a/posthog/temporal/tests/data_modeling/test_execute_dag_data_quality.py b/posthog/temporal/tests/data_modeling/test_execute_dag_data_quality.py
index a44b1271eed1..ea29f69b83e5 100644
--- a/posthog/temporal/tests/data_modeling/test_execute_dag_data_quality.py
+++ b/posthog/temporal/tests/data_modeling/test_execute_dag_data_quality.py
@@ -2,8 +2,10 @@ import uuid
import datetime as dt
import pytest
+from unittest.mock import patch
import temporalio.worker
+import temporalio.workflow
from temporalio import (
activity as temporal_activity,
workflow as temporal_workflow,
@@ -15,9 +17,12 @@ from posthog.temporal.data_modeling.activities.get_dag_structure import DAG as D
from posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputs, ExecuteDAGResult, ExecuteDAGWorkflow
from posthog.temporal.tests.data_modeling.test_execute_dag_workflow import (
MockMaterializeViewWorkflow,
+ _mock_workflow_should_block_on_quality,
_mock_workflow_should_fail,
+ _mock_workflow_should_self_audit,
stub_notify_dag_materialization_failures,
stub_preempt_dag_run,
+ stub_record_skipped_data_modeling_jobs,
)
from products.data_quality.backend.facade.contracts import MATERIALIZATION_GATE_ACTIVITY_NAME
@@ -26,6 +31,13 @@ pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
_suite_runs_started: list[dict] = []
+_MOCK_STATE = (
+ _suite_runs_started,
+ _mock_workflow_should_fail,
+ _mock_workflow_should_block_on_quality,
+ _mock_workflow_should_self_audit,
+)
+
@temporal_workflow.defn(name="data-quality-run-suite")
class MockCheckSuiteWorkflow:
@@ -38,11 +50,11 @@ class MockCheckSuiteWorkflow:
class TestPostMaterializationChecks:
@pytest.fixture(autouse=True)
def reset_mock_state(self):
- _suite_runs_started.clear()
- _mock_workflow_should_fail.clear()
+ for state in _MOCK_STATE:
+ state.clear()
yield
- _suite_runs_started.clear()
- _mock_workflow_should_fail.clear()
+ for state in _MOCK_STATE:
+ state.clear()
async def _run_dag(
self,
@@ -50,6 +62,7 @@ class TestPostMaterializationChecks:
node_ids: list[str],
*,
ephemeral_node_ids: list[str] | None = None,
+ edges: list[tuple[str, str]] | None = None,
register_suite: bool = True,
checks_needed: bool = True,
) -> ExecuteDAGResult:
@@ -60,7 +73,7 @@ class TestPostMaterializationChecks:
return DAGPlan(
nodes=executable,
executable_nodes=executable,
- edges=[],
+ edges=edges or [],
ephemeral_nodes=ephemeral_node_ids or [],
)
@@ -81,6 +94,7 @@ class TestPostMaterializationChecks:
stub_preempt_dag_run,
stub_get_dag_structure,
stub_materialization_gate,
+ stub_record_skipped_data_modeling_jobs,
stub_notify_dag_materialization_failures,
],
workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
@@ -125,3 +139,37 @@ class TestPostMaterializationChecks:
assert result.successful_nodes == 1
assert result.failed_nodes == 0
+
+ async def test_a_history_without_the_patch_marker_still_sweeps_every_node(self, ateam) -> None:
+ # An old DAG worker records the gate activity and suite child against a new child's
+ # quality_audited result. Filtering on replay would omit commands that history already has.
+ audited = str(uuid.uuid4())
+ _mock_workflow_should_self_audit.add(audited)
+
+ with patch.object(temporalio.workflow, "patched", return_value=False):
+ await self._run_dag(ateam.pk, [audited])
+
+ assert len(_suite_runs_started) == 1
+ assert _suite_runs_started[0]["node_ids"] == [audited]
+
+ async def test_a_node_that_audited_itself_is_not_swept_again(self, ateam) -> None:
+ audited, unaudited = str(uuid.uuid4()), str(uuid.uuid4())
+ _mock_workflow_should_self_audit.add(audited)
+
+ await self._run_dag(ateam.pk, [audited, unaudited])
+
+ assert len(_suite_runs_started) == 1
+ assert _suite_runs_started[0]["node_ids"] == [unaudited]
+
+ async def test_a_blocked_publish_stops_its_descendants_and_leaves_the_sweep(self, ateam) -> None:
+ blocked, downstream = str(uuid.uuid4()), str(uuid.uuid4())
+ _mock_workflow_should_block_on_quality.add(blocked)
+
+ result = await self._run_dag(ateam.pk, [blocked, downstream], edges=[(blocked, downstream)])
+
+ assert result.failed_nodes == 1
+ assert result.skipped_nodes == 1
+ skipped = next(node for node in result.node_results if node.skipped)
+ assert skipped.node_id == downstream
+ assert skipped.skip_reason == f"Upstream node {blocked} failed data quality checks"
+ assert _suite_runs_started == []
diff --git a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
index 39cd96b0d58f..cdd21d2d2460 100644
--- a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
+++ b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
@@ -501,6 +501,8 @@ class TestExecuteDAGWorkflow:
_mock_workflow_calls: list[str] = []
_mock_workflow_should_fail: set[str] = set()
+_mock_workflow_should_block_on_quality: set[str] = set()
+_mock_workflow_should_self_audit: set[str] = set()
_recorded_skipped_nodes: list[RecordSkippedDataModelingJobsInputs] = []
_notified_dag_failures: list[NotifyDAGMaterializationFailuresInputs] = []
@@ -523,11 +525,14 @@ class MockMaterializeViewWorkflow:
_mock_workflow_calls.append(inputs.node_id)
if inputs.node_id in _mock_workflow_should_fail:
raise temporalio.exceptions.ApplicationError(f"Node {inputs.node_id} failed")
+ blocked = inputs.node_id in _mock_workflow_should_block_on_quality
return MaterializeViewWorkflowResult(
job_id="test-job",
node_id=inputs.node_id,
rows_materialized=100,
duration_seconds=1.0,
+ quality_blocking_failures=1 if blocked else None,
+ quality_audited=blocked or inputs.node_id in _mock_workflow_should_self_audit,
)
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index 437ef00d23e4..e386969c6559 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -24,11 +24,13 @@ from posthog.temporal.data_modeling.activities import (
FailMaterializationInputs,
MaterializeViewInputs,
PrepareQueryableTableInputs,
+ QualityBlockMaterializationInputs,
SucceedMaterializationInputs,
create_data_modeling_job_activity,
fail_materialization_activity,
materialize_view_activity,
prepare_queryable_table_activity,
+ quality_block_materialization_activity,
succeed_materialization_activity,
)
from posthog.temporal.data_modeling.activities.materialize_view import (
@@ -519,6 +521,33 @@ class TestFailMaterializationActivity:
await database_sync_to_async(job.delete)()
+class TestQualityBlockMaterializationActivity:
+ async def test_a_blocked_publish_fails_the_node_and_job_but_starts_no_recovery(
+ self, activity_environment, ateam, anode, asaved_query, adag
+ ):
+ job = await _make_job(ateam, asaved_query, DataModelingJob.Status.RUNNING)
+ inputs = QualityBlockMaterializationInputs(
+ team_id=ateam.pk,
+ node_id=str(anode.id),
+ dag_id=str(adag.id),
+ job_id=str(job.id),
+ blocking_failures=2,
+ )
+
+ await activity_environment.run(quality_block_materialization_activity, inputs)
+
+ await database_sync_to_async(anode.refresh_from_db)()
+ await database_sync_to_async(job.refresh_from_db)()
+ system_props = anode.properties.get("system", {})
+ assert system_props["last_run_status"] == DataModelingJobStatus.FAILED
+ assert "2 data quality checks failed" in system_props["last_run_error"]
+ assert job.status == DataModelingJob.Status.FAILED
+ assert "2 data quality checks failed" in job.error
+ assert "suspended" not in system_props
+
+ await database_sync_to_async(job.delete)()
+
+
class TestShouldPauseScheduleForTimeout:
async def test_returns_false_when_fewer_than_5_previous_jobs(self, ateam, asaved_query):
from posthog.temporal.data_modeling.activities.fail_materialization import should_pause_schedule_for_timeout
@@ -697,6 +726,7 @@ class TestNodeSuspension:
"Abandoned: the materialization workflow is no longer running",
"QueueEmpty: Application error",
"Preempted: a new DAG run started before this job completed",
+ "Not published: 2 data quality checks failed. The previous version keeps serving until the checks pass.",
],
)
async def test_externally_aborted_failures_do_not_suspend(self, ateam, anode, asaved_query, adag, aborted_error):
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
index 0552b02b353d..c538b8888187 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
@@ -1,11 +1,17 @@
+import datetime as dt
+from contextlib import ExitStack
+
import pytest
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
import temporalio.workflow
-from temporalio.exceptions import WorkflowAlreadyStartedError
+from temporalio.exceptions import CancelledError, ChildWorkflowError, WorkflowAlreadyStartedError
from posthog.temporal.data_modeling.activities import (
FailMaterializationInputs,
+ MaterializeViewResult,
+ PrepareQueryableTableResult,
+ StageQueryableFilesResult,
SucceedMaterializationResult,
fail_materialization_activity,
)
@@ -15,6 +21,8 @@ from posthog.temporal.data_modeling.workflows.materialize_view import (
MaterializeViewWorkflowInputs,
)
+from products.data_quality.backend.facade.contracts import CHECK_SUITE_WORKFLOW_NAME, QualityAuditMode
+
pytestmark = pytest.mark.asyncio
WORKFLOW_MODULE = "posthog.temporal.data_modeling.workflows.materialize_view"
@@ -24,6 +32,248 @@ def _inputs() -> MaterializeViewWorkflowInputs:
return MaterializeViewWorkflowInputs(team_id=7, dag_id="dag-1", node_id="node-1")
+def _materialize_result(quality_audit: QualityAuditMode) -> MaterializeViewResult:
+ return MaterializeViewResult(
+ node_id="node-1",
+ node_name="orders",
+ row_count=10,
+ table_uri="s3://bucket/orders",
+ file_uris=["s3://bucket/orders/part-1.parquet"],
+ saved_query_id="sq-1",
+ quality_audit=quality_audit,
+ )
+
+
+class TestQualityGateBranching:
+ async def _run(
+ self,
+ activity_results: list,
+ child_result: dict | Exception,
+ *,
+ patched: bool = True,
+ shadow_handle: AsyncMock | None = None,
+ start_child: AsyncMock | None = None,
+ ) -> tuple:
+ execute_activity = AsyncMock(side_effect=activity_results)
+ child = (
+ AsyncMock(side_effect=child_result)
+ if isinstance(child_result, Exception)
+ else AsyncMock(return_value=child_result)
+ )
+ info = MagicMock()
+ info.parent = None
+ with ExitStack() as stack:
+ stack.enter_context(patch.object(temporalio.workflow, "execute_activity", new=execute_activity))
+ stack.enter_context(patch.object(temporalio.workflow, "execute_child_workflow", new=child))
+ stack.enter_context(
+ patch.object(temporalio.workflow, "start_child_workflow", new=start_child or AsyncMock())
+ )
+ stack.enter_context(patch.object(temporalio.workflow, "patched", return_value=patched))
+ stack.enter_context(patch.object(temporalio.workflow, "info", return_value=info))
+ stack.enter_context(patch.object(temporalio.workflow, "now", return_value=dt.datetime(2026, 8, 1)))
+ stack.enter_context(patch.object(temporalio.workflow, "logger"))
+ stack.enter_context(patch(f"{WORKFLOW_MODULE}.capture_exception"))
+ if shadow_handle is not None:
+ stack.enter_context(patch.object(temporalio.workflow, "start_activity", return_value=shadow_handle))
+ for metric in (
+ "get_node_finished_metric",
+ "get_node_duration_metric",
+ "get_node_rows_materialized_metric",
+ "get_node_storage_delta_mib_metric",
+ "get_node_total_storage_mib_metric",
+ "get_duckgres_shadow_finished_metric",
+ "get_clickhouse_materialization_duration_metric",
+ "get_duckgres_shadow_duration_metric",
+ "get_duckgres_shadow_rows_materialized_metric",
+ "get_duckgres_shadow_row_count_match_metric",
+ "get_duckgres_shadow_storage_mib_metric",
+ "get_duckgres_shadow_storage_delta_mib_metric",
+ ):
+ stack.enter_context(patch(f"{WORKFLOW_MODULE}.{metric}"))
+ result = await MaterializeViewWorkflow().run(_inputs())
+ return result, execute_activity
+
+ async def test_blocking_failures_stop_the_publish(self):
+ activity_results = [
+ False, # duckgres shadow check
+ "job-1", # create job
+ _materialize_result("gate"),
+ StageQueryableFilesResult(staged_folder_path="staged_1"),
+ None, # quality_block_materialization
+ ]
+
+ result, execute_activity = await self._run(activity_results, {"checks_failed_blocking": 2})
+
+ assert result.quality_blocking_failures == 2
+ assert result.quality_audited is True
+ started = [call.args[0].__name__ for call in execute_activity.await_args_list]
+ assert started[-2:] == ["stage_queryable_files_activity", "quality_block_materialization_activity"]
+ assert "publish_queryable_table_activity" not in started
+ assert "succeed_materialization_activity" not in started
+
+ async def test_a_passing_audit_publishes_and_succeeds(self):
+ activity_results = [
+ False,
+ "job-1",
+ _materialize_result("gate"),
+ StageQueryableFilesResult(staged_folder_path="staged_1"),
+ PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None), # publish
+ None, # succeed (pre-deploy shape is fine, enrichment skipped)
+ ]
+
+ result, execute_activity = await self._run(activity_results, {"checks_failed_blocking": 0})
+
+ assert result.quality_blocking_failures == 0
+ started = [call.args[0].__name__ for call in execute_activity.await_args_list]
+ assert "publish_queryable_table_activity" in started
+ assert "succeed_materialization_activity" in started
+
+ @pytest.mark.parametrize("mode", ["gate", "warn"])
+ async def test_a_history_without_the_patch_marker_adds_no_command(self, mode):
+ # A rolling deploy pairs an old workflow worker with a new activity worker, and the SDK
+ # drops the fields the old dataclass lacks. So a mode can reach a history that recorded
+ # only the prepare command, and replaying it here has to emit exactly that.
+ activity_results = [
+ False,
+ "job-1",
+ _materialize_result(mode),
+ PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None), # prepare
+ None, # succeed
+ ]
+ start_child = AsyncMock()
+
+ result, execute_activity = await self._run(
+ activity_results, {"checks_failed_blocking": 2}, patched=False, start_child=start_child
+ )
+
+ started = [call.args[0].__name__ for call in execute_activity.await_args_list]
+ assert "prepare_queryable_table_activity" in started
+ assert "stage_queryable_files_activity" not in started
+ assert "quality_block_materialization_activity" not in started
+ start_child.assert_not_awaited()
+ assert result.quality_blocking_failures is None
+ assert result.quality_audited is False
+
+ async def test_an_audit_that_reached_no_verdict_leaves_the_node_to_the_sweep(self):
+ # Returning zero here would publish and also claim the node was audited, so the DAG's
+ # fallback sweep would skip the one node whose checks never ran.
+ activity_results = [
+ False,
+ "job-1",
+ _materialize_result("gate"),
+ StageQueryableFilesResult(staged_folder_path="staged_1"),
+ PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None), # publish
+ None, # succeed
+ ]
+
+ result, execute_activity = await self._run(activity_results, RuntimeError("suite died"))
+
+ started = [call.args[0].__name__ for call in execute_activity.await_args_list]
+ assert "publish_queryable_table_activity" in started
+ assert result.quality_blocking_failures is None
+ assert result.quality_audited is False
+
+ @pytest.mark.parametrize(
+ "start_child,expected_audited",
+ [
+ (AsyncMock(), True),
+ (AsyncMock(side_effect=WorkflowAlreadyStartedError("id", "type")), True),
+ (AsyncMock(side_effect=RuntimeError("task queue is gone")), False),
+ ],
+ )
+ async def test_a_warn_suite_that_never_started_sends_the_node_back_to_the_sweep(
+ self, start_child, expected_audited
+ ) -> None:
+ activity_results = [
+ False,
+ "job-1",
+ _materialize_result("warn"),
+ PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None), # prepare
+ None, # succeed
+ ]
+
+ result, _ = await self._run(activity_results, {}, start_child=start_child)
+
+ assert result.quality_audited is expected_audited
+ assert result.quality_blocking_failures is None
+
+ async def test_a_blocked_publish_still_settles_the_duckgres_shadow(self):
+ # The blocked branch returns early. Leaving the shadow activity unawaited holds the parent
+ # DAG's concurrency slot and orphans the shadow job.
+ shadow_handle = AsyncMock()
+ shadow_handle.__await__ = lambda self=None: iter([])
+ activity_results = [
+ True, # duckgres shadow enabled
+ "duckgres-job-1", # create duckgres job
+ "job-1", # create clickhouse job
+ _materialize_result("gate"),
+ StageQueryableFilesResult(staged_folder_path="staged_1"),
+ None, # quality_block_materialization
+ ]
+
+ with patch.object(MaterializeViewWorkflow, "_collect_shadow_comparison", new=AsyncMock()) as collect:
+ result, _ = await self._run(activity_results, {"checks_failed_blocking": 1}, shadow_handle=shadow_handle)
+
+ assert result.quality_blocking_failures == 1
+ collect.assert_awaited_once()
+
+
+def _cancelled_child_error() -> ChildWorkflowError:
+ error = ChildWorkflowError(
+ "child cancelled",
+ namespace="default",
+ workflow_id="data-quality-gate-job-1",
+ run_id="run-1",
+ workflow_type=CHECK_SUITE_WORKFLOW_NAME,
+ initiated_event_id=1,
+ started_event_id=2,
+ retry_state=None,
+ )
+ error.__cause__ = CancelledError("cancelled")
+ return error
+
+
+class TestStagedAudit:
+ async def _staged_verdict(self, workflow: MaterializeViewWorkflow) -> int | None:
+ return await workflow._staged_audit_verdict(_inputs(), "job-1", _materialize_result("gate"), "staged_1")
+
+ async def test_reads_the_blocking_count_from_the_suite_result(self):
+ child = AsyncMock(return_value={"suite_run_id": "s-1", "status": "completed", "checks_failed_blocking": 3})
+ with patch.object(temporalio.workflow, "execute_child_workflow", new=child):
+ verdict = await self._staged_verdict(MaterializeViewWorkflow())
+
+ assert verdict == 3
+ assert child.await_args is not None
+ payload = child.await_args.args[1]
+ assert payload["saved_query_ids"] == ["sq-1"]
+ assert payload["staged_queryable_folder"] == "staged_1"
+
+ async def test_a_suite_that_errors_reaches_no_verdict(self):
+ with (
+ patch.object(
+ temporalio.workflow, "execute_child_workflow", new=AsyncMock(side_effect=RuntimeError("timeout"))
+ ),
+ patch.object(temporalio.workflow, "logger"),
+ patch(f"{WORKFLOW_MODULE}.capture_exception"),
+ ):
+ verdict = await self._staged_verdict(MaterializeViewWorkflow())
+
+ assert verdict is None
+
+ @pytest.mark.parametrize(
+ "cancellation",
+ [CancelledError("cancelled"), _cancelled_child_error()],
+ )
+ async def test_cancellation_is_not_a_verdict_to_fail_open_on(self, cancellation):
+ with (
+ patch.object(temporalio.workflow, "execute_child_workflow", new=AsyncMock(side_effect=cancellation)),
+ patch.object(temporalio.workflow, "logger"),
+ patch(f"{WORKFLOW_MODULE}.capture_exception"),
+ ):
+ with pytest.raises(type(cancellation)):
+ await self._staged_verdict(MaterializeViewWorkflow())
+
+
class TestFinalizeOrphanedDuckgresJob:
async def test_marks_orphaned_job_failed_without_touching_node(self):
workflow = MaterializeViewWorkflow()
diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.py
index 0ea1ad957008..949bdb7e691e 100644
--- a/products/data_quality/backend/facade/api.py
+++ b/products/data_quality/backend/facade/api.py
@@ -13,6 +13,7 @@ from ..logic.errors import CheckConfigError, SubjectUnresolvableError
from ..logic.registry import UnknownCheckTypeError, list_check_types
from ..logic.serialization import compute_fingerprint, from_config_entry, to_config_entry
from ..logic.subjects import resolve_subject
+from ..logic.triggers import materialization_audit_mode as quality_audit_mode
from .contracts import CheckTypeInfo
__all__ = [
@@ -26,6 +27,7 @@ __all__ = [
"compute_fingerprint",
"from_config_entry",
"list_check_types",
+ "quality_audit_mode",
"related_subject_ref",
"resolve_subject",
"to_config_entry",
diff --git a/products/data_quality/backend/facade/contracts.py b/products/data_quality/backend/facade/contracts.py
index affbe8871be8..69eb52244c9f 100644
--- a/products/data_quality/backend/facade/contracts.py
+++ b/products/data_quality/backend/facade/contracts.py
@@ -5,12 +5,23 @@ Frozen, framework-free values other products need. No Django imports.
"""
from dataclasses import dataclass, field
-from typing import Any
+from typing import Any, Literal, TypeGuard
CHECK_SUITE_WORKFLOW_NAME = "data-quality-run-suite"
MATERIALIZATION_GATE_ACTIVITY_NAME = "data-quality-materialization-gate"
+QualityAuditMode = Literal["skip", "warn", "gate"]
+
+QUALITY_AUDIT_SKIP: QualityAuditMode = "skip"
+QUALITY_AUDIT_WARN: QualityAuditMode = "warn"
+QUALITY_AUDIT_GATE: QualityAuditMode = "gate"
+
+
+def is_quality_audit_mode(value: str) -> TypeGuard[QualityAuditMode]:
+ """A recorded Temporal history can carry a mode another deploy defined and this one does not."""
+ return value in (QUALITY_AUDIT_SKIP, QUALITY_AUDIT_WARN, QUALITY_AUDIT_GATE)
+
@dataclass(frozen=True)
class CheckTypeInfo:
diff --git a/products/data_quality/backend/logic/runner.py b/products/data_quality/backend/logic/runner.py
index 2081b8031b15..117026a8ed22 100644
--- a/products/data_quality/backend/logic/runner.py
+++ b/products/data_quality/backend/logic/runner.py
@@ -10,10 +10,14 @@ check must not take down the rest of its suite.
import time
from dataclasses import dataclass, replace
from datetime import UTC, datetime
-from typing import Any
+from typing import TYPE_CHECKING, Any
+from posthog.hogql.context import HogQLContext
from posthog.hogql.query import execute_hogql_query
+if TYPE_CHECKING:
+ from posthog.hogql.database.database import Database
+
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models.scoping import team_scope
from posthog.models.team import Team
@@ -39,18 +43,24 @@ class CheckOutcome:
became_failing: bool = False
-def run_check(check: DataQualityCheck, suite_run: DataQualitySuiteRun, team: Team) -> CheckOutcome:
+def run_check(
+ check: DataQualityCheck,
+ suite_run: DataQualitySuiteRun,
+ team: Team,
+ database: "Database | None" = None,
+) -> CheckOutcome:
"""Compile, execute, and persist one check. Updates the check's denormalized status.
Runs under an explicit team scope because there is no request context out here, and saving a
check reads its own previous state through the fail-closed manager to build the activity log.
+ ``database`` overrides table resolution for write-audit-publish runs (see logic/staged_audit).
"""
started_at = datetime.now(UTC)
monotonic_start = time.monotonic()
previous_status = check.last_status
try:
- outcome = _execute(check, team)
+ outcome = _execute(check, team, database)
except Exception as err:
outcome = CheckOutcome(status=CheckRunStatus.ERRORED, error=str(err))
@@ -67,7 +77,21 @@ def run_check(check: DataQualityCheck, suite_run: DataQualitySuiteRun, team: Tea
return replace(outcome, became_failing=became_failing)
-def _execute(check: DataQualityCheck, team: Team) -> CheckOutcome:
+def record_unrunnable_check(
+ check: DataQualityCheck,
+ suite_run: DataQualitySuiteRun,
+ team: Team,
+ reason: str,
+) -> 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)
+ with team_scope(team.id):
+ _record_run(check, suite_run, outcome, datetime.now(UTC), duration_ms=0)
+ _update_check(check, outcome)
+ return outcome
+
+
+def _execute(check: DataQualityCheck, team: Team, database: "Database | None" = None) -> CheckOutcome:
if check.subject_uuid is None:
check.subject_status = SubjectStatus.ORPHANED
return CheckOutcome(status=CheckRunStatus.SKIPPED, error="The subject was deleted.")
@@ -96,7 +120,15 @@ def _execute(check: DataQualityCheck, team: Team) -> CheckOutcome:
data_quality_subject_type=subject.subject_type,
data_quality_subject_id=subject.subject_uuid,
):
- response = execute_hogql_query(query=compiled.query, team=team, query_type=QUERY_TYPE)
+ if database is not None:
+ response = execute_hogql_query(
+ query=compiled.query,
+ team=team,
+ query_type=QUERY_TYPE,
+ context=HogQLContext(team_id=team.pk, database=database),
+ )
+ else:
+ response = execute_hogql_query(query=compiled.query, team=team, query_type=QUERY_TYPE)
return _interpret(compiled, check.config, response.results, response.columns or [])
diff --git a/products/data_quality/backend/logic/staged_audit.py b/products/data_quality/backend/logic/staged_audit.py
new file mode 100644
index 000000000000..5ffbe6341dfc
--- /dev/null
+++ b/products/data_quality/backend/logic/staged_audit.py
@@ -0,0 +1,35 @@
+"""Point a subject's table at staged (unpublished) files, for write-audit-publish check runs."""
+
+from typing import TYPE_CHECKING
+from uuid import UUID
+
+from posthog.hogql.database.database import Database
+from posthog.hogql.database.s3_table import S3Table
+from posthog.hogql.modifiers import create_default_modifiers_for_team
+
+from products.data_modeling.backend.facade import api as data_modeling_facade
+
+if TYPE_CHECKING:
+ from posthog.models.team import Team
+
+
+def build_staged_database(team: "Team", saved_query_id: str | UUID, staged_queryable_folder: str) -> Database | None:
+ """None means there is no materialized table to repoint.
+
+ Callers must not fall back to the unmodified database, which reads the live view and so rules
+ on data the publish would not write.
+ """
+ summary = data_modeling_facade.get_saved_query_summary(team.pk, saved_query_id)
+ if summary is None:
+ return None
+
+ modifiers = create_default_modifiers_for_team(team)
+ database = Database.create_for(team=team, modifiers=modifiers)
+ try:
+ table = database.get_table(summary.name)
+ except Exception:
+ return None
+ if not isinstance(table, S3Table):
+ return None
+ table.queryable_folder = staged_queryable_folder
+ return database
diff --git a/products/data_quality/backend/logic/triggers.py b/products/data_quality/backend/logic/triggers.py
index fca6244734a3..01d5abd628a2 100644
--- a/products/data_quality/backend/logic/triggers.py
+++ b/products/data_quality/backend/logic/triggers.py
@@ -1,7 +1,7 @@
"""Gates the event-driven triggers consult before starting a check suite.
-Called from other products' pipelines (via inversion hooks), so they must be cheap, never raise,
-and answer false when the product flag is off.
+Called from other products' pipelines (via inversion hooks or facade functions), so they must be
+cheap, never raise, and answer the do-nothing value when the product flag is off.
"""
import uuid
@@ -9,6 +9,8 @@ from collections.abc import Iterable
from products.data_modeling.backend.facade import api as data_modeling_facade
+from ..facade.contracts import QUALITY_AUDIT_GATE, QUALITY_AUDIT_SKIP, QUALITY_AUDIT_WARN, QualityAuditMode
+from ..facade.enums import CheckSeverity
from .flags import is_data_quality_checks_enabled_for_team_id
@@ -35,3 +37,26 @@ def materialization_checks_needed(team_id: int, node_ids: Iterable["str | uuid.U
.filter(saved_query_id__in=saved_query_ids, enabled=True, deleted=False)
.exists()
)
+
+
+def materialization_audit_mode(team_id: int, saved_query_id: "str | uuid.UUID") -> QualityAuditMode:
+ """Gating needs an error-severity check as well as the team setting, because a warn-severity
+ failure cannot stop a publish and holding one behind an audit would only add latency.
+ """
+ from ..models import ( # noqa: PLC0415 — the app registry is not ready at import time
+ DataQualityCheck,
+ TeamDataQualityConfig,
+ )
+
+ if not is_data_quality_checks_enabled_for_team_id(team_id):
+ return QUALITY_AUDIT_SKIP
+ checks = DataQualityCheck.objects.for_team(team_id).filter(
+ saved_query_id=saved_query_id, enabled=True, deleted=False
+ )
+ if not checks.exists():
+ return QUALITY_AUDIT_SKIP
+ config = TeamDataQualityConfig.objects.filter(team_id=team_id).first()
+ gate_on = config is not None and config.gate_materialization_on_checks
+ if gate_on and checks.filter(severity=CheckSeverity.ERROR).exists():
+ return QUALITY_AUDIT_GATE
+ return QUALITY_AUDIT_WARN
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 0cb7a8d4d343..dbc97735ff72 100644
--- a/products/data_quality/backend/temporal/activities/run_check_batch.py
+++ b/products/data_quality/backend/temporal/activities/run_check_batch.py
@@ -1,5 +1,7 @@
from collections import Counter
+from django.db.models import QuerySet
+
from asgiref.sync import sync_to_async
from temporalio import activity
@@ -8,12 +10,15 @@ from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger
from ...facade.enums import CheckRunStatus, CheckSeverity
-from ...logic.runner import run_check
+from ...logic.runner import record_unrunnable_check, run_check
+from ...logic.staged_audit import build_staged_database
from ...models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun
from ..contracts import BatchOutcome, RunCheckBatchInputs
LOGGER = get_logger(__name__)
+STAGED_FILES_UNREADABLE = "The staged files could not be read, so this data was not audited."
+
@activity.defn
async def run_check_batch_activity(inputs: RunCheckBatchInputs) -> BatchOutcome:
@@ -21,6 +26,20 @@ async def run_check_batch_activity(inputs: RunCheckBatchInputs) -> BatchOutcome:
return await sync_to_async(_run_batch)(inputs)
+def _record_unaudited_batch(
+ checks: "QuerySet[DataQualityCheck]",
+ suite_run: DataQualitySuiteRun,
+ team: Team,
+) -> BatchOutcome:
+ """Error every check in the batch, leaving ``failed_blocking`` at zero so a gate publishes."""
+ errored = 0
+ for check in checks:
+ record_unrunnable_check(check, suite_run, team, STAGED_FILES_UNREADABLE)
+ errored += 1
+ LOGGER.warning("Could not audit staged files", suite_run_id=str(suite_run.id), checks=errored)
+ return BatchOutcome(errored=errored)
+
+
def _run_batch(inputs: RunCheckBatchInputs) -> BatchOutcome:
team = Team.objects.get(id=inputs.team_id)
suite_run = DataQualitySuiteRun.objects.for_team(inputs.team_id).get(id=inputs.suite_run_id)
@@ -32,11 +51,17 @@ def _run_batch(inputs: RunCheckBatchInputs) -> BatchOutcome:
suite_run=suite_run, quality_check_id__in=inputs.check_ids
).delete()
+ staged_database = None
+ if inputs.staged_queryable_folder and inputs.staged_saved_query_id:
+ staged_database = build_staged_database(team, inputs.staged_saved_query_id, inputs.staged_queryable_folder)
+ if staged_database is None:
+ return _record_unaudited_batch(checks, suite_run, team)
+
counts: Counter[str] = Counter()
failed_blocking = 0
newly_failing: list[str] = []
for check in checks:
- result = run_check(check, suite_run, team)
+ result = run_check(check, suite_run, team, database=staged_database)
counts[result.status] += 1
if result.status is CheckRunStatus.FAILED and check.severity == CheckSeverity.ERROR:
failed_blocking += 1
diff --git a/products/data_quality/backend/temporal/contracts.py b/products/data_quality/backend/temporal/contracts.py
index f821fc8eda25..1700c26e555f 100644
--- a/products/data_quality/backend/temporal/contracts.py
+++ b/products/data_quality/backend/temporal/contracts.py
@@ -29,6 +29,8 @@ class RunCheckSuiteInputs:
suite_run_id: str | None = None
data_modeling_job_id: str | None = None
created_by_id: int | None = None
+ # Audits the staged folder rather than the published table. Needs exactly one saved query.
+ staged_queryable_folder: str | None = None
@frozen
@@ -48,6 +50,8 @@ class RunCheckBatchInputs:
team_id: int
suite_run_id: str
check_ids: list[str]
+ staged_queryable_folder: str | None = None
+ staged_saved_query_id: str | None = None
@frozen
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 9170b8421082..d3eb3599cdd8 100644
--- a/products/data_quality/backend/temporal/workflows/run_check_suite.py
+++ b/products/data_quality/backend/temporal/workflows/run_check_suite.py
@@ -56,7 +56,7 @@ class RunCheckSuiteWorkflow(PostHogWorkflow):
retry_policy=RetryPolicy(maximum_attempts=3),
)
- outcomes = await self._run_batches(inputs.team_id, prepared)
+ outcomes = await self._run_batches(inputs, prepared)
return await workflow.execute_activity(
finalize_check_suite_activity,
FinalizeCheckSuiteInputs(team_id=inputs.team_id, suite_run_id=prepared.suite_run_id, outcomes=outcomes),
@@ -73,14 +73,23 @@ class RunCheckSuiteWorkflow(PostHogWorkflow):
)
raise
- async def _run_batches(self, team_id: int, prepared: PreparedSuite) -> list[BatchOutcome]:
+ async def _run_batches(self, inputs: RunCheckSuiteInputs, prepared: PreparedSuite) -> list[BatchOutcome]:
semaphore = asyncio.Semaphore(MAX_CONCURRENT_BATCHES)
+ staged_saved_query_id = (
+ inputs.saved_query_ids[0] if inputs.staged_queryable_folder and len(inputs.saved_query_ids) == 1 else None
+ )
async def _run(check_ids: list[str]) -> BatchOutcome:
async with semaphore:
return await workflow.execute_activity(
run_check_batch_activity,
- RunCheckBatchInputs(team_id=team_id, suite_run_id=prepared.suite_run_id, check_ids=check_ids),
+ RunCheckBatchInputs(
+ team_id=inputs.team_id,
+ suite_run_id=prepared.suite_run_id,
+ check_ids=check_ids,
+ staged_queryable_folder=inputs.staged_queryable_folder if staged_saved_query_id else None,
+ staged_saved_query_id=staged_saved_query_id,
+ ),
start_to_close_timeout=dt.timedelta(minutes=30),
heartbeat_timeout=dt.timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=2),
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 d241f7427c4d..608aa6cdaf0a 100644
--- a/products/data_quality/backend/tests/test_run_check_suite.py
+++ b/products/data_quality/backend/tests/test_run_check_suite.py
@@ -50,7 +50,9 @@ class _ActivityInfo:
class TestCheckSuiteActivities(BaseTest):
def setUp(self) -> None:
super().setUp()
- self.view = DataWarehouseSavedQuery.objects.create(team=self.team, name="orders", query={"kind": "HogQLQuery"})
+ self.view = DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="orders", query={"kind": "HogQLQuery", "query": "SELECT 1 AS customer_id"}
+ )
flag = patch(PREPARE_FLAG, return_value=True)
flag.start()
self.addCleanup(flag.stop)
@@ -170,6 +172,27 @@ class TestCheckSuiteActivities(BaseTest):
runs = DataQualityCheckRun.objects.for_team(self.team.id).filter(suite_run_id=prepared.suite_run_id)
assert list(runs.values_list("quality_check_id", flat=True)) == [stays.id]
+ def test_a_staged_audit_that_cannot_reach_the_staged_files_runs_no_check(self) -> None:
+ check = self._check()
+ prepared = self._prepare()
+
+ with patch(RUNNER_QUERY) as query:
+ outcome = _run_batch(
+ RunCheckBatchInputs(
+ team_id=self.team.id,
+ suite_run_id=prepared.suite_run_id,
+ check_ids=[str(check.id)],
+ staged_queryable_folder="query_2000000000000",
+ staged_saved_query_id=str(self.view.id),
+ )
+ )
+
+ query.assert_not_called()
+ assert (outcome.errored, outcome.failed_blocking) == (1, 0)
+ run = DataQualityCheckRun.objects.for_team(self.team.id).get(suite_run_id=prepared.suite_run_id)
+ assert run.status == CheckRunStatus.ERRORED
+ assert "staged files" in run.error
+
def test_finalize_sums_batch_outcomes_into_the_report(self) -> None:
prepared = self._prepare()
diff --git a/products/data_quality/backend/tests/test_staged_audit.py b/products/data_quality/backend/tests/test_staged_audit.py
new file mode 100644
index 000000000000..7c7be57879ca
--- /dev/null
+++ b/products/data_quality/backend/tests/test_staged_audit.py
@@ -0,0 +1,72 @@
+from posthog.test.base import BaseTest
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.printer.utils import prepare_and_print_ast
+
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.data_quality.backend.facade.api import compile_check
+from products.data_quality.backend.facade.enums import CheckType, SubjectType
+from products.data_quality.backend.logic.contracts import SubjectRef
+from products.data_quality.backend.logic.staged_audit import build_staged_database
+from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
+
+PUBLISHED_FOLDER = "query_1000000000000"
+STAGED_FOLDER = "query_2000000000000"
+
+
+class TestStagedAudit(BaseTest):
+ def _materialized_view(self) -> DataWarehouseSavedQuery:
+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="_key", access_secret="_secret")
+ backing_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=PUBLISHED_FOLDER,
+ )
+ return DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="orders",
+ query={"query": "SELECT 1 AS customer_id"},
+ columns={"customer_id": "String"},
+ table=backing_table,
+ is_materialized=True,
+ 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(
+ 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={})
+ 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.
+ return [str(value) for value in context.values.values()]
+
+ def test_the_audit_reads_the_staged_folder_not_the_published_one(self) -> None:
+ view = self._materialized_view()
+
+ urls = self._compiled_check_urls(view, STAGED_FOLDER)
+
+ assert any(STAGED_FOLDER in url for url in urls)
+ assert not any(PUBLISHED_FOLDER in url for url in urls)
+
+ def test_a_view_with_no_backing_table_gets_no_override(self) -> None:
+ view = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="orders",
+ query={"query": "SELECT 1 AS customer_id"},
+ columns={"customer_id": "String"},
+ )
+
+ assert build_staged_database(self.team, view.id, STAGED_FOLDER) is None
diff --git a/products/data_quality/backend/tests/test_triggers.py b/products/data_quality/backend/tests/test_triggers.py
index 391cc47a3b6f..7e207d4da949 100644
--- a/products/data_quality/backend/tests/test_triggers.py
+++ b/products/data_quality/backend/tests/test_triggers.py
@@ -7,9 +7,14 @@ from parameterized import parameterized
from products.data_modeling.backend.models import DAG, Node
from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
-from products.data_quality.backend.facade.enums import CheckType, SubjectType
-from products.data_quality.backend.logic.triggers import materialization_checks_needed, source_sync_checks_needed
-from products.data_quality.backend.models import DataQualityCheck
+from products.data_quality.backend.facade.contracts import QUALITY_AUDIT_GATE, QUALITY_AUDIT_SKIP, QUALITY_AUDIT_WARN
+from products.data_quality.backend.facade.enums import CheckSeverity, CheckType, SubjectType
+from products.data_quality.backend.logic.triggers import (
+ materialization_audit_mode,
+ materialization_checks_needed,
+ source_sync_checks_needed,
+)
+from products.data_quality.backend.models import DataQualityCheck, TeamDataQualityConfig
TRIGGER_FLAG = "products.data_quality.backend.logic.triggers.is_data_quality_checks_enabled_for_team_id"
@@ -72,3 +77,26 @@ class TestTriggerGates(BaseTest):
self._check(saved_query_id=None, table_id=table_id, subject_type=SubjectType.TABLE)
assert source_sync_checks_needed(self.team.id, table_id) is True
+
+ @parameterized.expand(
+ [
+ ("the_flag_is_off", {"severity": CheckSeverity.ERROR}, True, False, QUALITY_AUDIT_SKIP),
+ ("the_subject_has_no_check", None, True, True, QUALITY_AUDIT_SKIP),
+ ("the_team_never_configured_a_gate", {"severity": CheckSeverity.ERROR}, None, True, QUALITY_AUDIT_WARN),
+ ("the_team_turned_the_gate_off", {"severity": CheckSeverity.ERROR}, False, True, QUALITY_AUDIT_WARN),
+ ("every_check_only_warns", {"severity": CheckSeverity.WARN}, True, True, QUALITY_AUDIT_WARN),
+ ("a_check_can_block", {"severity": CheckSeverity.ERROR}, True, True, QUALITY_AUDIT_GATE),
+ ]
+ )
+ def test_audit_mode(self, _name, check_kwargs, gate_setting, flag_on, expected) -> None:
+ if check_kwargs is not None:
+ self._check(**check_kwargs)
+ if gate_setting is None:
+ TeamDataQualityConfig.objects.filter(team_id=self.team.id).delete()
+ else:
+ TeamDataQualityConfig.objects.update_or_create(
+ team=self.team, defaults={"gate_materialization_on_checks": gate_setting}
+ )
+
+ with patch(TRIGGER_FLAG, return_value=flag_on):
+ assert materialization_audit_mode(self.team.id, self.view.id) == expected