: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
refactor(data-quality): move check visibility behind the product facade (#90102)
Thiago Salvatore3f46e568956e
diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.pyindex e780dcada670..369e6042b79a 100644--- a/posthog/hogql/database/schema/information_schema.py+++ b/posthog/hogql/database/schema/information_schema.py@@ -970,6 +970,10 @@ def _references_denied_table(referenced_table_names: Optional[list[str]], deniedreturn False+def references_denied_table(referenced_table_names: Optional[list[str]], denied: set[str]) -> bool:+ return _references_denied_table(referenced_table_names, denied)++def _can_read_catalog(context: "HogQLContext") -> bool:"""Whether the caller has data_catalog read access, mirroring the REST viewset's resource gate.@@ -1074,24 +1078,6 @@ def _denial_applies(context: "HogQLContext", denied: set[str]) -> bool:return bool(denied) or data_quality.can_be_object_denied(_access_control(context))-def _visible_data_quality_checks(- context: "HogQLContext", team_id: int, checks: list[Any], denied: set[str]-) -> list[Any]:- """The checks a caller may see, by the same rule the REST surfaces apply.-- A check is out of reach on any of three counts: its own subject is unreadable, the definition it- would run next reads one that is, or the run behind its ``last_status`` read one.- """- from products.data_quality.backend.facade import api as data_quality # noqa: PLC0415-- if not _denial_applies(context, denied):- return checks- if context.database is None:- return []- hidden = data_quality.hidden_check_ids(team_id, checks, data_quality.denial_context(team_id, context.database))- return [check for check in checks if check.id not in hidden]--def _data_quality_checks(context: "HogQLContext", allowed: Optional[frozenset[str]]) -> list[list[Any]]:"""Load the team's data quality check definitions as information_schema rows (fail-soft).@@ -1105,10 +1091,19 @@ def _data_quality_checks(context: "HogQLContext", allowed: Optional[frozenset[stfrom products.data_quality.backend.facade.models import DataQualityCheck # noqa: PLC0415try:+ from products.data_quality.backend.facade import api as data_quality # noqa: PLC0415+denied = context.database._denied_tables if context.database is not None else set()queryset = DataQualityCheck.objects.for_team(team_id).filter(deleted=False).order_by("-created_at")if allowed is not None:queryset = queryset.filter(name__in=allowed)+ checks = list(queryset)+ if _denial_applies(context, denied):+ if context.database is None:+ return []+ checks = data_quality.visible_checks(+ team_id, checks, data_quality.denial_context(team_id, context.database)+ )return [[str(check.id),@@ -1126,30 +1121,13 @@ def _data_quality_checks(context: "HogQLContext", allowed: Optional[frozenset[stcheck.last_run_at.isoformat() if check.last_run_at else None,check.created_at.isoformat(),]- for check in _visible_data_quality_checks(context, team_id, list(queryset), denied)+ for check in checks]except Exception:logger.exception("information_schema: failed to load data quality checks", team_id=team_id)return []-def _without_denied_runs(team_id: int, runs: Any, database: Any) -> Any:- """Exclude, in SQL, every run that touched a subject the caller may not read.-- A run is judged on the subjects its own columns record -- the one it declared and each it read --- by the same rule the REST routes apply, so the two surfaces cannot come to different answers- about the same run. Editing a check therefore cannot rewrite what its history discloses, and- deleting a subject cannot free its name for something else to answer for it.-- Held up against a snapshot of the subjects the team has, so the cost tracks the warehouse rather- than the length of retained history -- which matters here because this runs before the window- that bounds the rows served.- """- from products.data_quality.backend.facade import api as data_quality # noqa: PLC0415-- return runs.exclude(data_quality.unreadable_runs_q(data_quality.denial_context(team_id, database)))--def _data_quality_check_runs(context: "HogQLContext", allowed: Optional[frozenset[str]]) -> list[list[Any]]:"""Load the team's most recent check executions as information_schema rows (fail-soft).@@ -1163,6 +1141,8 @@ def _data_quality_check_runs(context: "HogQLContext", allowed: Optional[frozensefrom products.data_quality.backend.facade.models import DataQualityCheckRun # noqa: PLC0415try:+ from products.data_quality.backend.facade import api as data_quality # noqa: PLC0415+denied = context.database._denied_tables if context.database is not None else set()base = DataQualityCheckRun.objects.for_team(team_id)if allowed is not None:@@ -1176,7 +1156,7 @@ def _data_quality_check_runs(context: "HogQLContext", allowed: Optional[frozenseif _denial_applies(context, denied):if context.database is None:return []- base = _without_denied_runs(team_id, base, context.database)+ base = data_quality.without_denied_runs(base, data_quality.denial_context(team_id, context.database))return [[str(run.id),@@ -1214,12 +1194,21 @@ def _data_quality_health(context: "HogQLContext", allowed: Optional[frozenset[stfrom products.data_quality.backend.facade.models import DataQualityCheck # noqa: PLC0415try:+ from products.data_quality.backend.facade import api as data_quality # noqa: PLC0415+denied = context.database._denied_tables if context.database is not None else set()checks_qs = DataQualityCheck.objects.for_team(team_id).filter(deleted=False, enabled=True)if allowed is not None:checks_qs = checks_qs.filter(subject_name__in=allowed)+ checks = list(checks_qs)+ if _denial_applies(context, denied):+ if context.database is None:+ return []+ checks = data_quality.visible_checks(+ team_id, checks, data_quality.denial_context(team_id, context.database)+ )by_subject: dict[tuple[str, str], list[Any]] = defaultdict(list)- for check in _visible_data_quality_checks(context, team_id, list(checks_qs), denied):+ for check in checks:# A hard-deleted subject has no id to key a rollup on, and its checks only skip.if check.subject_uuid is None:continuediff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.pyindex 9b8dd402217d..d449b30b46ec 100644--- a/products/data_quality/backend/facade/api.py+++ b/products/data_quality/backend/facade/api.py@@ -34,18 +34,13 @@ from ..logic.subject_access import (ReferencedSubjects,caller_denial_context,can_be_object_denied,- check_type_reads_beyond_subject,definition_reads_unreadable_subject,denial_context,denied_subject_names,- hidden_check_ids,- is_subject_denied,- referenced_subject_names,- referenced_subjects,- referencing_check_types,suites_backing_unreadable_runs_q,- unreadable_runs_q,unreadable_suites_q,+ visible_checks,+ without_denied_runs,)from ..logic.subjects import resolve_subjectfrom ..logic.triggers import materialization_audit_mode as quality_audit_mode@@ -67,7 +62,6 @@ __all__ = ["UnknownCheckTypeError","caller_denial_context","can_be_object_denied",- "check_type_reads_beyond_subject","checks_for_subject","compile_check","compute_fingerprint",@@ -79,15 +73,10 @@ __all__ = ["ensure_name_available","from_config_entry","get_gate_config",- "hidden_check_ids",- "is_subject_denied","list_check_types","notify_materialization_blocked","quality_audit_mode","record_check_run",- "referenced_subject_names",- "referenced_subjects",- "referencing_check_types","related_subject_ref","resolve_subject","roll_up_health",@@ -98,8 +87,9 @@ __all__ = ["subject_locations","suites_backing_unreadable_runs_q","to_config_entry",- "unreadable_runs_q","unreadable_suites_q","upsert_check","validate_check",+ "visible_checks",+ "without_denied_runs",]diff --git a/products/data_quality/backend/logic/subject_access.py b/products/data_quality/backend/logic/subject_access.pyindex 7db8cef5fd96..183ece14da07 100644--- a/products/data_quality/backend/logic/subject_access.py+++ b/products/data_quality/backend/logic/subject_access.py@@ -13,13 +13,13 @@ know is absent from that snapshot and therefore out of reach.import jsonfrom collections.abc import Sequence-from typing import TYPE_CHECKING, Any, Optional+from typing import TYPE_CHECKING, Any, Optional, TypeVarfrom uuid import UUID-from django.db.models import Exists, OuterRef, Q+from django.db.models import Exists, OuterRef, Q, QuerySetfrom posthog.hogql.database.database import Database-from posthog.hogql.database.schema.information_schema import _references_denied_table+from posthog.hogql.database.schema.information_schema import references_denied_tablefrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exception@@ -42,6 +42,7 @@ if TYPE_CHECKING:_SUBJECT_TYPE_KEY = "subject_type"_SUBJECT_UUID_KEY = "subject_uuid"+_RunQS = TypeVar("_RunQS", bound=QuerySet)def denied_subject_names(@@ -57,7 +58,7 @@ def denied_subject_names(def is_subject_denied(subject_name: str, denied: set[str]) -> bool:"""Whether a check's subject is in the caller's denied set, matched the same way the loaders match."""- return _references_denied_table([subject_name], denied)+ return references_denied_table([subject_name], denied)def can_be_object_denied(user_access_control: Optional["UserAccessControl"]) -> bool:@@ -168,6 +169,21 @@ def unreadable_runs_q(context: DenialContext) -> Q:return unreadable_declared | unknowable_references | unreadable_references+def without_denied_runs(runs: _RunQS, context: DenialContext) -> _RunQS:+ """Exclude, in SQL, every run that touched a subject the caller may not read.++ A run is judged on the subjects its own columns record -- the one it declared and each it read --+ by the same rule the REST routes apply, so the two surfaces cannot come to different answers+ about the same run. Editing a check therefore cannot rewrite what its history discloses, and+ deleting a subject cannot free its name for something else to answer for it.++ Held up against a snapshot of the subjects the team has, so the cost tracks the warehouse rather+ than the length of retained history -- which matters here because this runs before the window+ that bounds the rows served.+ """+ return runs.exclude(unreadable_runs_q(context))++def unreadable_suites_q(context: DenialContext) -> Q:"""Match, in SQL, every suite whose own subject this caller may not read.@@ -211,6 +227,16 @@ def hidden_check_ids(team_id: int, checks: Sequence[DataQualityCheck], context:)+def visible_checks(team_id: int, checks: Sequence[DataQualityCheck], context: DenialContext) -> list[DataQualityCheck]:+ """The checks a caller may see, by the same rule the REST surfaces apply.++ A check is out of reach on any of three counts: its own subject is unreadable, the definition it+ would run next reads one that is, or the run behind its ``last_status`` read one.+ """+ hidden = hidden_check_ids(team_id, checks, context)+ return [check for check in checks if check.id not in hidden]++def definition_reads_unreadable_subject(team_id: int, check_type: str, config: dict[str, Any], context: DenialContext) -> bool:diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.pyindex bf780e29fbd4..053f45a9dc0b 100644--- a/products/data_quality/backend/presentation/views.py+++ b/products/data_quality/backend/presentation/views.py@@ -121,14 +121,15 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):def _hidden_check_ids(self, checks: list[DataQualityCheck]) -> set[UUID]:# The same rule the information_schema loaders apply, so REST and SQL cannot come to# different answers about the same check.- return api.hidden_check_ids(self.team_id, checks, self._denial_context())+ visible = api.visible_checks(self.team_id, checks, self._denial_context())+ return {check.id for check in checks} - {check.id for check in visible}def _readable_runs(self, runs: QuerySet[DataQualityCheckRun]) -> QuerySet[DataQualityCheckRun]:# Excluded in SQL rather than per page, so a run that read a subject out of reach is gone# before the window that bounds what is served.if not self._can_be_object_denied():return runs- return runs.exclude(api.unreadable_runs_q(self._denial_context()))+ return api.without_denied_runs(runs, self._denial_context())def _require_referenced_subject_access(self, check_type: str, config: dict) -> None:"""403 a definition that reads a subject the caller cannot be shown to be allowed.