: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): invert the denial gate to a readable-subject snapshot (#89690)
Thiago Salvatoref87d42c6694a
diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.pyindex 4fa10e38ef71..e780dcada670 100644--- a/posthog/hogql/database/schema/information_schema.py+++ b/posthog/hogql/database/schema/information_schema.py@@ -19,8 +19,6 @@ import hashlibfrom collections import defaultdictfrom typing import TYPE_CHECKING, Any, NamedTuple, Optional-from django.db.models import Q-import structlogfrom posthog.hogql import ast@@ -1079,55 +1077,19 @@ def _denial_applies(context: "HogQLContext", denied: set[str]) -> bool: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 rule the REST surfaces apply.-- A check is out of reach on any of three counts: its own subject is denied, the definition it- would run next reads one that is, or the run behind its ``last_status`` read one. The row is both- tenses at once, so the definition is judged by the names it resolves today and the run by the- identities it pinned.+ """The checks a caller may see, by the same rule the REST surfaces apply.- Subject names come from the subjects themselves rather than the copy denormalized onto the check,- which only a run rewrites, so a rename cannot carry a denied subject back into a list.+ 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: PLC0415if not _denial_applies(context, denied):return checks- recordings = data_quality.latest_run_recordings(team_id, [check.id for check in checks])- current_names = data_quality.resolve_subject_names(- team_id,- [- data_quality.subject_identity(check.subject_type, check.subject_uuid)- for check in checks- if check.subject_uuid- ]- + data_quality.pinned_subject_refs(recording.referenced_subjects for recording in recordings.values()),- )- return [- check- for check in checks- if not _references_denied_table(- [- current_names.get(- data_quality.subject_identity(check.subject_type, check.subject_uuid), check.subject_name- )- ],- denied,- )- and not data_quality.check_reads_denied_subject(team_id, check.check_type, check.config, denied)- and not _last_run_read_a_denied_subject(recordings.get(check.id), current_names, denied)- ]---def _last_run_read_a_denied_subject(recording: Any, current_names: dict[Any, str], denied: set[str]) -> bool:- from products.data_quality.backend.facade import api as data_quality # noqa: PLC0415-- # A check that never ran carries no verdict, so there is nothing here to authorize.- if recording is None:- return False- return data_quality.run_reads_unreadable_subject(- recording.check_type, recording.referenced_subjects, current_names, denied- )+ 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]]:@@ -1171,55 +1133,21 @@ def _data_quality_checks(context: "HogQLContext", allowed: Optional[frozenset[streturn []-def _without_denied_runs(team_id: int, runs: Any, denied: set[str]) -> Any:- """Exclude, in SQL, every run that read a subject the caller is denied.+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 identities it pinned as it executed, 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. A referencing run that pinned nothing predates the- recording and is withheld rather than assumed harmless.+ 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.- Only the types that can read past their own subject reach the recording scan. A run of any other- type is readable whatever it recorded, and the aggregation this narrows runs over the team's- whole retained history before the window applies.+ 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- subjects = set(runs.values_list("subject_type", "subject_uuid", "subject_name").distinct())- recordings = list(- runs.filter(check_type__in=data_quality.referencing_check_types())- .values_list("check_type", "referenced_subjects")- .distinct()- )- current_names = data_quality.resolve_subject_names(- team_id,- [data_quality.subject_identity(subject_type, subject_uuid) for subject_type, subject_uuid, _ in subjects]- + data_quality.pinned_subject_refs(recorded for _, recorded in recordings),- )- blocked_subjects = [- subject_uuid- for subject_type, subject_uuid, stamped in subjects- if _references_denied_table(- [current_names.get(data_quality.subject_identity(subject_type, subject_uuid), stamped)], denied- )- ]- if blocked_subjects:- runs = runs.exclude(subject_uuid__in=blocked_subjects)-- blocked_recordings = Q()- for check_type, recorded in recordings:- if not data_quality.run_reads_unreadable_subject(check_type, recorded, current_names, denied):- continue- # A JSONField compares None against JSON null, not against the SQL NULL a run without a- # recording stores, so the two cases cannot share one lookup.- if recorded is None:- blocked_recordings |= Q(check_type=check_type, referenced_subjects__isnull=True)- else:- blocked_recordings |= Q(check_type=check_type, referenced_subjects=recorded)- if blocked_recordings:- runs = runs.exclude(blocked_recordings)- return runs+ 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]]:@@ -1246,7 +1174,9 @@ def _data_quality_check_runs(context: "HogQLContext", allowed: Optional[frozense# Never on the denied set alone: deleting the subject a caller was denied is what empties it,# which is the case this withholds runs for.if _denial_applies(context, denied):- base = _without_denied_runs(team_id, base, denied)+ if context.database is None:+ return []+ base = _without_denied_runs(team_id, base, context.database)return [[str(run.id),diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex 5be42de0f60d..9174bfa91efb 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -28,7 +28,8 @@ _LAZY = {"get_saved_query_columns": "logic.saved_query_reads","get_saved_query_ids_for_nodes": "logic.saved_query_reads","get_saved_query_summary": "logic.saved_query_reads",- "saved_query_names": "logic.saved_query_reads",+ "all_saved_query_names": "logic.saved_query_reads",+ "backing_table_ids_by_saved_query": "logic.saved_query_reads","saved_query_materialized_at": "logic.saved_query_freshness","latest_saved_query_materialization_job": "logic.saved_query_freshness","is_materialization_fresh": "logic.saved_query_freshness",diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.pyindex d6c05955ad38..3c2cf0d3dddd 100644--- a/products/data_modeling/backend/logic/saved_query_reads.py+++ b/products/data_modeling/backend/logic/saved_query_reads.py@@ -55,22 +55,30 @@ def get_saved_query_summary(team_id: int, saved_query_id: UUID | str) -> SavedQu)-def saved_query_names(team_id: int, saved_query_ids: Iterable[UUID | str]) -> dict[str, str]:- """The current name of each saved query that still resolves. One query; anything gone is absent.+def all_saved_query_names(team_id: int) -> dict[str, str]:+ """The current name of every saved query in this team that still resolves. One query."""+ rows = DataWarehouseSavedQuery.objects.filter(team_id=team_id).exclude(deleted=True).values_list("id", "name")+ return {str(saved_query_id): name for saved_query_id, name in rows}+- The bulk form of ``get_saved_query_summary`` for a caller that only needs names, so authorizing- a page of stored references costs one query rather than one per reference. Soft-deleted rows are- excluded for the same reason: ``soft_delete`` rewrites ``name`` to a tombstone.+def backing_table_ids_by_saved_query(team_id: int) -> dict[UUID, UUID]:+ """Private backing table ids mapped to their saved query ids. One query.++ Includes soft-deleted saved queries because deleting a view leaves its backing table behind.+ The URL predicate deliberately matches the HogQL catalog's private-backing-table exclusion."""- ids = [str(saved_query_id) for saved_query_id in saved_query_ids]- if not ids:- return {}- rows = (- DataWarehouseSavedQuery.objects.filter(team_id=team_id, id__in=ids)- .exclude(deleted=True)- .values_list("id", "name")+ saved_queries = (+ DataWarehouseSavedQuery.objects.filter(team_id=team_id, table__isnull=False)+ .select_related("table")+ .only("id", "team_id", "table_id", "table__url_pattern"))- return {str(saved_query_id): name for saved_query_id, name in rows}+ return {+ saved_query.table_id: saved_query.id+ for saved_query in saved_queries+ if saved_query.table_id is not None+ and saved_query.table is not None+ and saved_query.folder_path in saved_query.table.url_pattern+ }def get_materialized_table_uri(team_id: int, saved_query_id: UUID | str) -> str | None:diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.pyindex 490b5483d7b6..9b8dd402217d 100644--- a/products/data_quality/backend/facade/api.py+++ b/products/data_quality/backend/facade/api.py@@ -8,12 +8,10 @@ data. ORM model classes never cross here either -- ``facade/models.py`` is their"""from ..logic.checks import (- RunRecording,checks_for_subject,edit_check,empty_check_suite,ensure_name_available,- latest_run_recordings,soft_delete_check,start_check_suite,subject_health,@@ -22,29 +20,34 @@ from ..logic.checks import ()from ..logic.compiler import compile_check, related_subject_reffrom ..logic.config import get_gate_config, set_gate_materialization_on_checks-from ..logic.contracts import CompiledCheck, SubjectIdentity, SubjectRef+from ..logic.contracts import CompiledCheck, SubjectReffrom ..logic.errors import CheckConfigError, CheckEditConflict, SubjectUnresolvableErrorfrom ..logic.health import CheckStatusRow, roll_up_healthfrom ..logic.navigation import SubjectKey, SubjectLocation, subject_locationsfrom ..logic.notifications import notify_materialization_blockedfrom ..logic.registry import UnknownCheckTypeError, list_check_types+from ..logic.run_records import record_check_runfrom ..logic.serialization import compute_fingerprint, from_config_entry, to_config_entryfrom ..logic.subject_access import (+ DenialContext,+ ReadableSubjects,ReferencedSubjects,+ caller_denial_context,can_be_object_denied,- check_reads_denied_subject,check_type_reads_beyond_subject,+ definition_reads_unreadable_subject,+ denial_context,denied_subject_names,+ hidden_check_ids,is_subject_denied,- pinned_subject_refs,- pinned_subjects,referenced_subject_names,referenced_subjects,referencing_check_types,- run_reads_unreadable_subject,- unconfirmable_subject_names,+ suites_backing_unreadable_runs_q,+ unreadable_runs_q,+ unreadable_suites_q,)-from ..logic.subjects import resolve_subject, resolve_subject_names, subject_identity+from ..logic.subjects import resolve_subjectfrom ..logic.triggers import materialization_audit_mode as quality_audit_modefrom .contracts import CheckTypeInfo@@ -54,49 +57,49 @@ __all__ = ["CheckStatusRow","CheckTypeInfo","CompiledCheck",+ "DenialContext",+ "ReadableSubjects","ReferencedSubjects",- "RunRecording",- "SubjectIdentity","SubjectKey","SubjectLocation","SubjectRef","SubjectUnresolvableError","UnknownCheckTypeError",+ "caller_denial_context","can_be_object_denied",- "check_reads_denied_subject","check_type_reads_beyond_subject","checks_for_subject","compile_check","compute_fingerprint",+ "definition_reads_unreadable_subject",+ "denial_context","denied_subject_names","edit_check","empty_check_suite","ensure_name_available","from_config_entry","get_gate_config",+ "hidden_check_ids","is_subject_denied",- "latest_run_recordings","list_check_types","notify_materialization_blocked",- "pinned_subject_refs",- "pinned_subjects","quality_audit_mode",+ "record_check_run","referenced_subject_names","referenced_subjects","referencing_check_types","related_subject_ref","resolve_subject",- "resolve_subject_names","roll_up_health",- "run_reads_unreadable_subject","set_gate_materialization_on_checks","soft_delete_check","start_check_suite","subject_health",- "subject_identity","subject_locations",+ "suites_backing_unreadable_runs_q","to_config_entry",- "unconfirmable_subject_names",+ "unreadable_runs_q",+ "unreadable_suites_q","upsert_check","validate_check",]diff --git a/products/data_quality/backend/logic/checks.py b/products/data_quality/backend/logic/checks.pyindex 86ac82590f55..619e20fbd08a 100644--- a/products/data_quality/backend/logic/checks.py+++ b/products/data_quality/backend/logic/checks.py@@ -300,16 +300,8 @@ def checks_for_subject(return queryset if include_deleted else queryset.filter(deleted=False)-@frozen-class RunRecording:- """What a run recorded about the subjects it read, for judging the row it is denormalized onto."""-- check_type: str- referenced_subjects: list | None---def latest_run_recordings(team_id: int, check_ids: Iterable[UUID]) -> dict[UUID, RunRecording]:- """What each of these checks last read, keyed by check. One query; a check never run is absent.+def latest_run_ids(team_id: int, check_ids: Iterable[UUID]) -> list[UUID]:+ """The id of each of these checks' most recent run. One query; a check never run contributes none.A check row is not purely a definition: its ``last_status`` and ``last_run_at`` come from thisrun, so they report on whatever it read. Authorizing the row on the definition alone would serve@@ -317,18 +309,14 @@ def latest_run_recordings(team_id: int, check_ids: Iterable[UUID]) -> dict[UUID,"""ids = list(check_ids)if not ids:- return {}- latest = (+ return []+ return list(DataQualityCheckRun.objects.for_team(team_id).filter(quality_check_id__in=ids).order_by("quality_check_id", "-created_at").distinct("quality_check_id")- .values_list("quality_check_id", "check_type", "referenced_subjects")+ .values_list("id", flat=True))- return {- check_id: RunRecording(check_type=check_type, referenced_subjects=referenced)- for check_id, check_type, referenced in latest- }def subject_health(team_id: int, subject_type: str, subject_uuid: str | UUID) -> SubjectHealth:diff --git a/products/data_quality/backend/logic/run_records.py b/products/data_quality/backend/logic/run_records.pynew file mode 100644index 000000000000..0b03b0786f8d--- /dev/null+++ b/products/data_quality/backend/logic/run_records.py@@ -0,0 +1,61 @@+"""Write one check execution down.++The columns a run records are what every history gate later judges it by, so the field list is+spelled out here rather than forwarded as ``**kwargs``: a caller that omits the declared subject or+misspells ``referenced_subjects`` would strand its own history behind a fail-closed gate.+"""++from datetime import datetime+from typing import Any+from uuid import UUID++from ..facade.enums import CheckRunStatus, CheckSeverity+from ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+++def record_check_run(+ team_id: int,+ *,+ suite_run: DataQualitySuiteRun,+ subject_type: str,+ subject_uuid: str | UUID,+ subject_name: str,+ check_type: str,+ check_fingerprint: str,+ status: CheckRunStatus | str,+ quality_check: DataQualityCheck | None = None,+ column_name: str = "",+ check_config: dict[str, Any] | None = None,+ check_severity: CheckSeverity | str | None = None,+ referenced_subjects: list[dict[str, str]] | None = None,+ failed_row_count: int | None = None,+ observed_value: float | None = None,+ compiled_query: str = "",+ error: str = "",+ duration_ms: int | None = None,+ started_at: datetime | None = None,+ finished_at: datetime | None = None,+) -> DataQualityCheckRun:+ """Record one check execution."""+ return DataQualityCheckRun.objects.for_team(team_id).create(+ team_id=team_id,+ suite_run=suite_run,+ subject_type=subject_type,+ subject_uuid=subject_uuid,+ subject_name=subject_name,+ check_type=check_type,+ check_fingerprint=check_fingerprint,+ status=status,+ quality_check=quality_check,+ column_name=column_name,+ check_config=check_config,+ check_severity=check_severity,+ referenced_subjects=referenced_subjects,+ failed_row_count=failed_row_count,+ observed_value=observed_value,+ compiled_query=compiled_query,+ error=error,+ duration_ms=duration_ms,+ started_at=started_at,+ finished_at=finished_at,+ )diff --git a/products/data_quality/backend/logic/runner.py b/products/data_quality/backend/logic/runner.pyindex 389e9acd2b7b..f5bd70093a4e 100644--- a/products/data_quality/backend/logic/runner.py+++ b/products/data_quality/backend/logic/runner.py@@ -24,10 +24,11 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom ..facade.enums import CheckRunStatus, CheckSeverity, SubjectStatus, SuiteRunTrigger-from ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from ..models import DataQualityCheck, DataQualitySuiteRunfrom .compiler import compile_check, related_subject_reffrom .contracts import CompiledCheck, Evaluationfrom .notifications import notify_check_started_failing+from .run_records import record_check_runfrom .staged_audit import StagedSubjectOverride, build_staged_databasefrom .subject_access import check_type_reads_beyond_subject, pin_referenced_subjectsfrom .subjects import resolve_subject@@ -318,8 +319,8 @@ def _record_run() -> None:if check.subject_uuid is None:return- DataQualityCheckRun.objects.for_team(check.team_id).create(- team_id=check.team_id,+ record_check_run(+ check.team_id,quality_check=check,suite_run=suite_run,subject_type=check.subject_type,diff --git a/products/data_quality/backend/logic/subject_access.py b/products/data_quality/backend/logic/subject_access.pyindex 4905d33c45f3..7db8cef5fd96 100644--- a/products/data_quality/backend/logic/subject_access.py+++ b/products/data_quality/backend/logic/subject_access.py@@ -1,23 +1,35 @@-"""Which check subjects the caller may not read.+"""Which check subjects the caller may read, and what that hides.The REST endpoint and the ``information_schema.data_quality_*`` tables must never disagree onvisibility, so both resolve denial from the same source: the warehouse-table denial the HogQLdatabase computes for the caller. A member denied a table or view must not read its checks, runhistory, or health rollup -- those carry the compiled ``config``, failed-row counts, and observedvalues, which together act as a count oracle over rows the member cannot read directly.++Every verdict here is the negation of an explicit readable predicate, over a snapshot of the+subjects the caller may read. A subject that is denied, deleted, or of a kind this gate does not+know is absent from that snapshot and therefore out of reach."""-from collections.abc import Iterable, Mapping+import json+from collections.abc import Sequencefrom typing import TYPE_CHECKING, Any, Optionalfrom uuid import UUID+from django.db.models import Exists, OuterRef, Q+from posthog.hogql.database.database import Databasefrom posthog.hogql.database.schema.information_schema import _references_denied_tablefrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exception+from products.data_modeling.backend.facade import api as data_modeling_facade+from products.warehouse_sources.backend.facade import api as warehouse_facade+from ..facade.enums import SubjectType+from ..models import DataQualityCheck, DataQualityCheckRun+from .checks import latest_run_idsfrom .contracts import SubjectIdentityfrom .registry import all_specs, get_specfrom .spec import CheckTypeSpec@@ -28,6 +40,9 @@ if TYPE_CHECKING:from products.access_control.backend.facade.user_access_control import UserAccessControl+_SUBJECT_TYPE_KEY = "subject_type"+_SUBJECT_UUID_KEY = "subject_uuid"+def denied_subject_names(team: "Team", user: "User", user_access_control: Optional["UserAccessControl"] = None@@ -60,6 +75,176 @@ def can_be_object_denied(user_access_control: Optional["UserAccessControl"]) ->)+@frozen+class ReadableSubjects:+ """The warehouse subjects this caller may read, by id.++ A snapshot of what exists *and* is allowed right now. Absence is the single verdict every gate+ negates: a denied subject is absent because its name matched the denial set, a deleted one+ because it no longer exists, and a subject of a kind this gate does not know because neither+ branch below claims it.+ """++ table_ids: frozenset[UUID]+ view_ids: frozenset[UUID]++ def contains(self, subject_type: str, subject_uuid: str | UUID | None) -> bool:+ if subject_uuid is None:+ return False+ try:+ identifier = UUID(str(subject_uuid))+ except ValueError:+ return False+ if subject_type == SubjectType.TABLE:+ return identifier in self.table_ids+ if subject_type == SubjectType.VIEW:+ return identifier in self.view_ids+ return False+++@frozen+class DenialContext:+ """Everything a gate needs about one caller, resolved once and passed down.++ ``readable`` answers the identity-keyed questions a stored row asks, ``denied`` the name-keyed+ ones a definition asks, and ``database`` is the caller's own HogQL database -- carried so a+ surface that has already built one never builds a second.+ """++ readable: ReadableSubjects+ denied: set[str]+ database: Database+++def readable_subjects(team_id: int, denied: set[str]) -> ReadableSubjects:+ """The team's live warehouse subjects, minus the ones this caller is denied. Four queries.++ Cost tracks the objects the team has, not the length of retained history, which is what makes+ it safe to hold a whole page of run history up against.+ """+ tables = warehouse_facade.all_queryable_table_names(team_id)+ views = data_modeling_facade.all_saved_query_names(team_id)+ excluded_table_ids = set(data_modeling_facade.backing_table_ids_by_saved_query(team_id))+ excluded_table_ids.update(warehouse_facade.direct_access_table_ids(team_id))+ return ReadableSubjects(+ table_ids=frozenset(+ table_id+ for table_id, name in tables.items()+ if table_id not in excluded_table_ids and not is_subject_denied(name, denied)+ ),+ view_ids=frozenset(UUID(view_id) for view_id, name in views.items() if not is_subject_denied(name, denied)),+ )+++def denial_context(team_id: int, database: Database) -> DenialContext:+ """The caller's denial state, from a HogQL database that has already been built for them."""+ denied = set(database._denied_tables)+ return DenialContext(readable=readable_subjects(team_id, denied), denied=denied, database=database)+++def caller_denial_context(+ team: "Team", user: "User", user_access_control: Optional["UserAccessControl"] = None+) -> DenialContext:+ """The caller's denial state, building the HogQL database this request will reuse."""+ return denial_context(team.id, Database.create_for(team=team, user=user, user_access_control=user_access_control))+++def unreadable_runs_q(context: DenialContext) -> Q:+ """Match, in SQL, every run that touched a subject this caller may not read.++ Judged from the run's own columns, so the answer holds for a run whose definition was edited or+ hard-deleted, and a surface can exclude before a window or a page count. Three ways out of reach:++ - the subject the run declared is not readable, which covers denied and deleted alike;+ - it recorded no references and its type can read past its own subject, so what it read cannot+ be established at all;+ - it recorded references that are not all readable.+ """+ unreadable_declared = ~_readable_subject_q(context.readable)+ unknowable_references = Q(referenced_subjects__isnull=True, check_type__in=referencing_check_types())+ unreadable_references = ~Q(referenced_subjects__isnull=True) & ~Q(+ referenced_subjects__contained_by=_readable_identities(context.readable)+ )+ return unreadable_declared | unknowable_references | unreadable_references+++def unreadable_suites_q(context: DenialContext) -> Q:+ """Match, in SQL, every suite whose own subject this caller may not read.++ Only a suite that targets exactly one subject records one. A sweep across several records none,+ so it is judged by the runs it covers instead and must not be matched here.+ """+ return Q(subject_uuid__isnull=False) & ~_readable_subject_q(context.readable)+++def suites_backing_unreadable_runs_q(team_id: int, context: DenialContext) -> Q:+ """Match, in SQL, every suite that covers a run this caller may not read.++ A suite row carries passed/failed/errored/skipped over every check it ran, while its run list+ hands back only the readable ones, so serving both names the withheld run's outcome by+ subtraction. Correlated per suite rather than collected across the project first, so a page costs+ an index probe per suite it examines instead of a pass over retained history.+ """+ covered = DataQualityCheckRun.objects.for_team(team_id).filter(+ unreadable_runs_q(context), suite_run_id=OuterRef("pk")+ )+ return Q(Exists(covered))+++def hidden_check_ids(team_id: int, checks: Sequence[DataQualityCheck], context: DenialContext) -> set[UUID]:+ """The ids of the checks this caller may not see, over a page of them.++ 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. The row is both+ tenses at once, so each is judged by the rule for its own tense -- the definition by the names it+ resolves today, the stored run by the identities it recorded.+ """+ hidden = {check.id for check in checks if not context.readable.contains(check.subject_type, check.subject_uuid)}+ verdicts: dict[str, bool] = {}+ for check in checks:+ if check.id in hidden:+ continue+ if _memoized_definition_verdict(team_id, check.check_type, check.config or {}, context, verdicts):+ hidden.add(check.id)+ return hidden | _checks_whose_latest_run_is_unreadable(+ team_id, [check.id for check in checks if check.id not in hidden], context+ )+++def definition_reads_unreadable_subject(+ team_id: int, check_type: str, config: dict[str, Any], context: DenialContext+) -> bool:+ """Whether the definition a check would run next reads a subject beyond a caller's reach.++ The parent is not the only subject a check reads: a ``relationships`` check names a second+ subject and a ``custom_sql`` query selects arbitrary tables, both run by the worker with team+ scope only. Relationship targets are judged by their configured identity; custom SQL references+ are matched by name because the query names them rather than pinning them. A name that is denied,+ that no longer resolves, or that resolves to neither an allowed nor a denied object proves+ nothing in the caller's favor.+ """+ if not check_type_reads_beyond_subject(check_type):+ return False+ refs = referenced_subjects(team_id, check_type, config)+ if refs.related_subject is not None and not context.readable.contains(+ refs.related_subject.subject_type, refs.related_subject.subject_uuid+ ):+ return True+ if any(is_subject_denied(name, context.denied) for name in refs.names):+ return True+ return bool(unconfirmable_subject_names(refs.names, context.database))+++def unconfirmable_subject_names(names: tuple[str, ...], database: Database) -> set[str]:+ """The referenced names this caller can neither resolve nor be shown to have been denied.++ Deleting a warehouse object takes its denial with it: the name leaves the database the caller+ can resolve *and* the denial set that is rebuilt from the objects that still exist, so a check+ that once read a denied table starts reading as harmless. Neither state proves access, so both+ are reported and the caller fails them closed."""+ return {name for name in names if not database.has_table(name) and not database.is_table_access_denied(name)}++# A check type reads beyond its declared subject only if it overrides one of these hooks: a# ``relationships`` check names a target subject, a ``custom_sql`` query selects arbitrary tables.# Derived from the specs rather than hard-coded so a new referencing type can't silently slip the net.@@ -74,40 +259,29 @@ _REFERENCING_CHECK_TYPES: frozenset[str] = frozenset(def check_type_reads_beyond_subject(check_type: str) -> bool:"""Whether this check type can read warehouse objects other than its declared subject.- Used to fail closed when a run's definition was hard-deleted: without the config we can no longer- enumerate the referenced subjects, so a ``relationships`` or ``custom_sql`` run must be treated as- if it could touch a denied one."""+ Used to fail closed when a run recorded no references: without them we cannot enumerate what a+ ``relationships`` or ``custom_sql`` run touched, so it is treated as if it could have touched+ anything."""return check_type in _REFERENCING_CHECK_TYPESdef referencing_check_types() -> frozenset[str]:"""The check types that read beyond their declared subject (``relationships``, ``custom_sql``).- A cheap pre-filter so a denied-reference scan only parses the config of checks that can carry one,- rather than every check on the team."""+ A cheap pre-filter so a scan only parses the config of checks that can carry a reference, rather+ than every check on the team."""return _REFERENCING_CHECK_TYPES-def check_reads_denied_subject(team_id: int, check_type: str, config: dict[str, Any], denied: set[str]) -> bool:- """Whether a check reads any subject *besides its declared one* that the caller is denied.-- The single test the health rollup and suite-summary guards share, so the REST endpoint and the- ``information_schema`` tables stay in lock-step about which referencing checks a member may see."""- if not denied:- return False- return any(is_subject_denied(name, denied) for name in referenced_subject_names(team_id, check_type, config))--@frozenclass ReferencedSubjects:- """What a check reads besides its declared subject, and whether that could be established.+ """What a check reads besides its declared subject, by name and configured identity.- ``unresolved_reference`` is the part a name list cannot carry: a ``relationships`` target that no- longer resolves leaves no name behind, so a caller matching names alone would read "references- nothing" from a subject that was deleted out from under the denial set."""+ ``related_subject`` keeps a ``relationships`` target as the identity its config stores, so+ authorization does not need to resolve it through a mutable name."""names: tuple[str, ...]- unresolved_reference: bool+ related_subject: SubjectIdentity | Nonedef referenced_subjects(team_id: int, check_type: str, config: dict[str, Any]) -> ReferencedSubjects:@@ -119,24 +293,25 @@ def referenced_subjects(team_id: int, check_type: str, config: dict[str, Any]) -a count oracle over one the author cannot read. Assumes config already validated."""spec = get_spec(check_type)parsed = spec.parse_config(config)- names = list(spec.referenced_table_names(parsed))- unresolved = False- if related := spec.related_subject_ref(parsed):- ref = resolve_subject(team_id, related[0], related[1])- if ref.exists:- names.append(ref.name)- else:- unresolved = True- return ReferencedSubjects(names=tuple(names), unresolved_reference=unresolved)+ related_subject = (+ SubjectIdentity(subject_type=str(related[0]), subject_uuid=str(related[1]))+ if (related := spec.related_subject_ref(parsed))+ else None+ )+ return ReferencedSubjects(names=tuple(spec.referenced_table_names(parsed)), related_subject=related_subject)def referenced_subject_names(team_id: int, check_type: str, config: dict[str, Any]) -> list[str]:"""The names from :func:`referenced_subjects`, for callers that only report or match on them."""- return list(referenced_subjects(team_id, check_type, config).names)---_SUBJECT_TYPE_KEY = "subject_type"-_SUBJECT_UUID_KEY = "subject_uuid"+ referenced = referenced_subjects(team_id, check_type, config)+ names = list(referenced.names)+ if referenced.related_subject is not None:+ related = resolve_subject(+ team_id, referenced.related_subject.subject_type, referenced.related_subject.subject_uuid+ )+ if related.exists:+ names.append(related.name)+ return namesdef pin_referenced_subjects(team_id: int, check_type: str, config: dict[str, Any]) -> list[dict[str, str]] | None:@@ -147,14 +322,21 @@ def pin_referenced_subjects(team_id: int, check_type: str, config: dict[str, Anyrun read over an object they were denied. An identity survives that: the reused name resolves toa different id, and the recorded id stops resolving.+ Every entry carries both keys and nothing else. The gate that reads these asks whether each entry+ is contained in the caller's readable set, and a partial entry is contained in more than it should+ be, so this shape is the guard.+``None`` when the references cannot be established at all, so a reader falls back to judging therun by its type rather than reading an empty list as "read nothing"."""try:spec = get_spec(check_type)parsed = spec.parse_config(config)+ backing_tables = data_modeling_facade.backing_table_ids_by_saved_query(team_id)pinned = [- subject for name in spec.referenced_table_names(parsed) if (subject := _pin_name(team_id, name)) is not None+ subject+ for name in spec.referenced_table_names(parsed)+ if (subject := _pin_name(team_id, name, backing_tables)) is not None]if related := spec.related_subject_ref(parsed):pinned.append(SubjectIdentity(subject_type=str(related[0]), subject_uuid=str(related[1])))@@ -164,84 +346,48 @@ def pin_referenced_subjects(team_id: int, check_type: str, config: dict[str, Anyreturn [{_SUBJECT_TYPE_KEY: subject.subject_type, _SUBJECT_UUID_KEY: subject.subject_uuid} for subject in pinned]-def pinned_subjects(recorded: Any) -> list[SubjectIdentity] | None:- """The identities a run recorded, or None when it recorded nothing judgeable.+def _readable_subject_q(readable: ReadableSubjects) -> Q:+ return Q(subject_type=SubjectType.TABLE, subject_uuid__in=readable.table_ids) | Q(+ subject_type=SubjectType.VIEW, subject_uuid__in=readable.view_ids+ )- A malformed entry reads as nothing recorded rather than as an empty list, so a run whose- recording cannot be trusted falls back to the same type-based rule as one predating it. An- entry is only judgeable if it can be resolved, so the type and the id are validated here rather- than left to raise on whichever surface reads the column."""- if not isinstance(recorded, list):- return None- subjects: list[SubjectIdentity] = []- for entry in recorded:- if not isinstance(entry, dict):- return None- subject_type, subject_uuid = entry.get(_SUBJECT_TYPE_KEY), entry.get(_SUBJECT_UUID_KEY)- if not isinstance(subject_type, str) or not isinstance(subject_uuid, str):- return None- if not _is_resolvable(subject_type, subject_uuid):- return None- subjects.append(SubjectIdentity(subject_type=subject_type, subject_uuid=subject_uuid))- return subjects---def pinned_subject_refs(recordings: Iterable[Any]) -> list[SubjectIdentity]:- """Every identity across these recordings, for one bulk name resolution over a page of runs."""- return [subject for recorded in recordings for subject in pinned_subjects(recorded) or []]---def run_reads_unreadable_subject(- check_type: str, recorded: Any, current_names: Mapping[SubjectIdentity, str], denied: set[str]-) -> bool:- """Whether a recorded run read a subject the caller cannot be shown to be allowed.- The one test every surface serving run history applies, so the REST routes and the- ``information_schema`` loaders cannot come to different answers about the same run. Judged from- the identities the run pinned as it executed: never from the definition its check carries now,- which an edit rewrites, and never from names, which deleting an object frees for anyone to take.+def _readable_identities(readable: ReadableSubjects) -> list[dict[str, str]]:+ return [+ {_SUBJECT_TYPE_KEY: str(subject_type), _SUBJECT_UUID_KEY: str(subject_uuid)}+ for subject_type, ids in ((SubjectType.TABLE, readable.table_ids), (SubjectType.VIEW, readable.view_ids))+ for subject_uuid in ids+ ]- A subject missing from ``current_names`` no longer resolves, and took its denial with it, so- nothing left can show the caller was allowed it. A run that pinned nothing predates the- recording and is judged by its type instead: one that cannot read past its own subject read only- the subject this surface already authorized, and anything that can is withheld.- """- pinned = pinned_subjects(recorded)- if pinned is None:- return check_type_reads_beyond_subject(check_type)- return any((name := current_names.get(subject)) is None or is_subject_denied(name, denied) for subject in pinned)+def _checks_whose_latest_run_is_unreadable(+ team_id: int, check_ids: Sequence[UUID], context: DenialContext+) -> set[UUID]:+ run_ids = latest_run_ids(team_id, check_ids)+ if not run_ids:+ return set()+ unreadable = (+ DataQualityCheckRun.objects.for_team(team_id)+ .filter(id__in=run_ids)+ .filter(unreadable_runs_q(context))+ .values_list("quality_check_id", flat=True)+ )+ return {check_id for check_id in unreadable if check_id is not None}-def _is_resolvable(subject_type: str, subject_uuid: str) -> bool:- try:- SubjectType(subject_type)- UUID(subject_uuid)- except ValueError:- return False- return True++def _memoized_definition_verdict(+ team_id: int, check_type: str, config: dict[str, Any], context: DenialContext, verdicts: dict[str, bool]+) -> bool:+ key = json.dumps([check_type, config], sort_keys=True, default=str)+ if key not in verdicts:+ verdicts[key] = definition_reads_unreadable_subject(team_id, check_type, config, context)+ return verdicts[key]-def _pin_name(team_id: int, name: str) -> SubjectIdentity | None:+def _pin_name(team_id: int, name: str, backing_tables: dict[UUID, UUID]) -> SubjectIdentity | None:ref = resolve_subject_by_name(team_id, name)if ref is None:return None+ if ref.subject_type == SubjectType.TABLE and (saved_query_id := backing_tables.get(UUID(ref.subject_uuid))):+ return SubjectIdentity(subject_type=str(SubjectType.VIEW), subject_uuid=str(saved_query_id))return SubjectIdentity(subject_type=str(ref.subject_type), subject_uuid=ref.subject_uuid)---def unconfirmable_subject_names(- team: "Team",- user: "User",- names: tuple[str, ...],- user_access_control: Optional["UserAccessControl"] = None,-) -> set[str]:- """The referenced names this caller can neither resolve nor be shown to have been denied.-- Deleting a warehouse object takes its denial with it: the name leaves the database the caller- can resolve *and* the denial set that is rebuilt from the objects that still exist, so a run- that once read a denied table starts reading as harmless. Neither state proves access, so both- are reported and the caller fails them closed -- the same stance ``_require_parent_subject_access``- already takes for the subject a check hangs off."""- if not names:- return set()- database = Database.create_for(team=team, user=user, user_access_control=user_access_control)- return {name for name in names if not database.has_table(name) and not database.is_table_access_denied(name)}diff --git a/products/data_quality/backend/logic/subjects.py b/products/data_quality/backend/logic/subjects.pyindex 286f33d9cccd..e9300e4a8c64 100644--- a/products/data_quality/backend/logic/subjects.py+++ b/products/data_quality/backend/logic/subjects.py@@ -6,7 +6,6 @@ cross the product boundary. A subject that no longer resolves marks the check ordenormalized name is refreshed on every run so renames self-heal."""-from collections.abc import Iterablefrom uuid import UUIDfrom products.data_modeling.backend.facade import api as data_modeling_facade@@ -14,7 +13,7 @@ from products.warehouse_sources.backend.facade import api as warehouse_facadefrom products.warehouse_sources.backend.facade.contracts import WAREHOUSE_OBJECT_TABLE, WAREHOUSE_OBJECT_VIEWfrom ..facade.enums import SubjectType-from .contracts import SubjectIdentity, SubjectRef+from .contracts import SubjectRef_WAREHOUSE_OBJECT_SUBJECT_TYPES = {WAREHOUSE_OBJECT_TABLE: SubjectType.TABLE,@@ -76,32 +75,6 @@ def _resolve_view(team_id: int, subject_uuid: str | UUID) -> SubjectRef:)-def resolve_subject_names(team_id: int, subjects: Iterable[SubjectIdentity]) -> dict[SubjectIdentity, str]:- """The current name of every subject that still resolves, keyed by identity. Two queries.-- Authorization has to read the name the subject carries *now*, because denial is computed from- the names that exist today. The name denormalized onto a check is only rewritten when the check- runs, so a subject renamed since would otherwise stop matching its own denial. A subject that no- longer resolves is absent rather than empty, so a caller can tell the two apart.- """- wanted = set(subjects)- view_ids = [subject.subject_uuid for subject in wanted if subject.subject_type == SubjectType.VIEW]- table_ids = [UUID(subject.subject_uuid) for subject in wanted if subject.subject_type == SubjectType.TABLE]-- names: dict[SubjectIdentity, str] = {- SubjectIdentity(subject_type=SubjectType.VIEW.value, subject_uuid=saved_query_id): name- for saved_query_id, name in data_modeling_facade.saved_query_names(team_id, view_ids).items()- }- for table_id, name in warehouse_facade.queryable_table_names(team_id, table_ids).items():- names[SubjectIdentity(subject_type=SubjectType.TABLE.value, subject_uuid=str(table_id))] = name- return names---def subject_identity(subject_type: str, subject_uuid: str | UUID) -> SubjectIdentity:- """The identity of a subject as a row records it, from whichever form the caller holds."""- return SubjectIdentity(subject_type=str(subject_type), subject_uuid=str(subject_uuid))--def subject_column_type(team_id: int, subject_type: str, subject_uuid: str | UUID, column_name: str) -> str | None:"""The column's ClickHouse type, or None when the subject or the column cannot be established.diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.pyindex 79111707cfeb..bf780e29fbd4 100644--- a/products/data_quality/backend/presentation/views.py+++ b/products/data_quality/backend/presentation/views.py@@ -13,7 +13,8 @@ from collections.abc import Callablefrom typing import ClassVar, castfrom uuid import UUID-from django.db.models import Q, QuerySet+from django.db.models import QuerySet+from django.shortcuts import get_object_or_404from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view@@ -48,26 +49,7 @@ from .serializers import ()_RECENT_RUNS_LIMIT = 50--# An empty Q() matches every row, so an exclusion built by ORing clauses has to start from one that-# matches none, or a page with nothing to withhold would withhold all of it.-_MATCHES_NOTHING = Q(pk__in=[])---def _current_subject_name(check: DataQualityCheck, current_names: dict[api.SubjectIdentity, str]) -> str:- # A hard-deleted subject nulls the FK, leaving nothing to resolve and only the name the last run- # stamped on the check.- if check.subject_uuid is None:- return check.subject_name- return current_names.get(api.subject_identity(check.subject_type, check.subject_uuid), check.subject_name)---def _matches_recording(check_type: str, recorded: list | None) -> Q:- # A JSONField compares None against JSON null, not against the SQL NULL a run without a- # recording stores, so the two cases cannot share one lookup.- if recorded is None:- return Q(check_type=check_type, referenced_subjects__isnull=True)- return Q(check_type=check_type, referenced_subjects=recorded)+_LAST_RUN_FIELDS = ("last_status", "last_run_at", "last_succeeded_at")class _QualityGatedViewSet(TeamAndOrgViewSetMixin):@@ -114,163 +96,63 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):# gate applies to as well as on what it decides.return api.can_be_object_denied(self.user_access_control)- def _denied_subject_names(self) -> set[str]:- # Same denial the information_schema loaders read. Computed once per request.- cached = getattr(self, "_denied_subjects_cache", None)+ def _denial_context(self) -> api.DenialContext:+ """The subjects this caller may read, and the names they are denied. Once per request.++ Only ever called behind ``_can_be_object_denied``: for anyone else there is nothing to+ decide, and the snapshot is not cheap enough to build for them.+ """+ cached = getattr(self, "_denial_context_cache", None)if cached is None:- # A warehouse subject can only be denied to a non-admin in an org with access controls, so- # skip the (heavy) database build otherwise -- the denied set would be empty either way,- # which keeps this in lock-step with the loaders rather than diverging from them.- if not self._can_be_object_denied():- cached = set()- else:- try:- cached = api.denied_subject_names(- self.team,- cast(User, self.request.user),- user_access_control=self.user_access_control,- )- except Exception as err:- # Building the denial set walks every saved query; one malformed definition must- # not 500 the surface. Failing open would leak denied subjects, so fail closed.- capture_exception(err)- raise PermissionDenied("Could not verify your access to this table or view.")- self._denied_subjects_cache = cached+ try:+ cached = api.caller_denial_context(+ self.team,+ cast(User, self.request.user),+ user_access_control=self.user_access_control,+ )+ except Exception as err:+ # Building the snapshot walks every saved query; one malformed definition must not+ # 500 the surface. Failing open would leak denied subjects, so fail closed.+ capture_exception(err)+ raise PermissionDenied("Could not verify your access to this table or view.")+ self._denial_context_cache = cachedreturn cached- def _reads_unreadable_subject(self, check_type: str, config: dict) -> bool:- """Whether this definition reads a subject the caller cannot be shown to be allowed.+ 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())++ 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()))++ 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.The parent is not the only subject a check reads: a relationships check names a secondsubject and a custom_sql query selects arbitrary tables, both run by the worker with teamscope only. Authorize them too, or a check on an allowed subject is a count oracle over adenied one.- A denied name is only the case where the subject still exists. Deleting it takes its denial- with it, so a name that neither resolves nor is denied proves nothing either way and is- refused on the same fail-closed terms.+ The verdict is a pure function of the definition, so a page or a suite that carries the same+ one many times parses and resolves it once."""- # A type that cannot read past its own subject has nothing here to authorize. The verdict on- # one that can is a pure function of its definition, so a project-wide page parses and- # resolves each distinct definition once rather than once per check carrying it.- if not api.check_type_reads_beyond_subject(check_type):- return False- cache: dict[str, bool] = getattr(self, "_reads_unreadable_cache", {})- self._reads_unreadable_cache = cache+ if not self._can_be_object_denied():+ return+ cache: dict[str, bool] = getattr(self, "_definition_verdicts", {})+ self._definition_verdicts = cachekey = json.dumps([check_type, config], sort_keys=True, default=str)if key not in cache:- cache[key] = self._definition_reads_unreadable_subject(check_type, config)- return cache[key]-- def _definition_reads_unreadable_subject(self, check_type: str, config: dict) -> bool:- refs = api.referenced_subjects(self.team.id, check_type, config)- if refs.unresolved_reference:- return True- if any(api.is_subject_denied(name, self._denied_subject_names()) for name in refs.names):- return True- return bool(self._unconfirmable_names(refs.names))-- def _unconfirmable_names(self, names: tuple[str, ...]) -> set[str]:- # Memoized per request: the lookup rebuilds the caller's HogQL database, and a suite re-runs- # the same definitions.- cache: dict[str, bool] = getattr(self, "_unconfirmable_cache", {})- self._unconfirmable_cache = cache- unseen = tuple(name for name in names if name not in cache)- if unseen:- unconfirmable = api.unconfirmable_subject_names(- self.team,- cast(User, self.request.user),- unseen,- user_access_control=self.user_access_control,+ cache[key] = api.definition_reads_unreadable_subject(+ self.team_id, check_type, config, self._denial_context())- cache.update({name: name in unconfirmable for name in unseen})- return {name for name in names if cache[name]}-- def _require_referenced_subject_access(self, check_type: str, config: dict) -> None:- if not self._can_be_object_denied():- return- if self._reads_unreadable_subject(check_type, config):+ if cache[key]:raise PermissionDenied("You don't have access to a table or view this check reads.")- def _denied_checks(self, checks: list[DataQualityCheck], denied: set[str]) -> set[UUID]:- """The ids of the checks this caller may not see, over a page of them.-- A check is out of reach on any of three counts: its own subject is denied, the definition it- would run next reads one that is, or the run behind its ``last_status`` read one. The row is- both tenses at once -- a definition and the verdict of a past run -- so each is judged by the- rule for its own tense, the definition by the names it resolves today and the run by the- identities it pinned.-- Subject names come from the subjects themselves rather than from the copy denormalized onto- the check, which only a run rewrites, so a rename cannot carry a denied subject back into a- list.- """- recordings = api.latest_run_recordings(self.team_id, [check.id for check in checks])- subjects = [- api.subject_identity(check.subject_type, check.subject_uuid) for check in checks if check.subject_uuid- ]- subjects += api.pinned_subject_refs(recording.referenced_subjects for recording in recordings.values())- current_names = api.resolve_subject_names(self.team_id, subjects)- return {- check.id- for check in checks- if api.is_subject_denied(_current_subject_name(check, current_names), denied)- or self._reads_unreadable_subject(check.check_type, check.config)- or self._last_run_read_an_unreadable_subject(recordings.get(check.id), current_names, denied)- }-- def _last_run_read_an_unreadable_subject(- self, recording: api.RunRecording | None, current_names: dict[api.SubjectIdentity, str], denied: set[str]- ) -> bool:- # A check that never ran carries no verdict, so there is nothing here to authorize.- if recording is None:- return False- return api.run_reads_unreadable_subject(- recording.check_type, recording.referenced_subjects, current_names, denied- )-- def _denied_definitions(self, runs: QuerySet[DataQualityCheckRun]) -> Q:- """Match the runs that read a subject the caller is denied.-- Keyed on the identities each run pinned, so the suites reporting on it are withheld by the- same rule the routes serving it apply. Each distinct recording is judged once and every- identity resolves in one pass. A referencing run that pinned nothing is matched too, since- what it read cannot be established.-- Only the types that can read past their own subject reach the scan. A run of any other type- pinned an empty list, or pinned nothing and falls back to its type, so it is readable- whatever it recorded -- and the aggregation this narrows runs over the team's whole history.- """- runs = runs.filter(check_type__in=api.referencing_check_types())- recordings = list(runs.values_list("check_type", "referenced_subjects").distinct())- current_names = api.resolve_subject_names(- self.team_id, api.pinned_subject_refs(recorded for _, recorded in recordings)- )- denied = self._denied_subject_names()- matched = _MATCHES_NOTHING- for check_type, recorded in recordings:- if api.run_reads_unreadable_subject(check_type, recorded, current_names, denied):- matched |= _matches_recording(check_type, recorded)- return matched-- def _readable_runs(self, runs: list[DataQualityCheckRun]) -> list[DataQualityCheckRun]:- """Drop the runs that read a subject the caller cannot be shown to be allowed.-- Every identity in the page resolves in one pass rather than one query per run, since a- suite re-runs the same checks over the same subjects.- """- if not self._can_be_object_denied():- return runs- current_names = api.resolve_subject_names(- self.team_id, api.pinned_subject_refs(run.referenced_subjects for run in runs)- )- denied = self._denied_subject_names()- return [- run- for run in runs- if not api.run_reads_unreadable_subject(run.check_type, run.referenced_subjects, current_names, denied)- ]-class _SubjectScopedViewSet(_QualityGatedViewSet):"""Adds the parent-subject gate for viewsets nested under a warehouse saved query or table."""@@ -287,24 +169,16 @@ class _SubjectScopedViewSet(_QualityGatedViewSet):self._require_parent_subject_access()def _require_parent_subject_access(self) -> None:- """403 a denied parent -- for every action, including list.+ """403 a parent this caller may not read -- for every action, including list.A member denied a view must not be able to enumerate its check configs or counts through- this surface. Orphan-tolerant rather than 404ing: a parent that no longer resolves still- serves its checks (they are skipped, not hidden), because resolution carries no RBAC to- enforce and orphaned history must stay reachable -- but only for a caller who cannot be- object-denied, since an orphan has no name left to check a denial against.+ this surface. A parent that no longer resolves is out of reach on the same terms: deleting+ it takes its denial with it, so nothing left can show the caller was allowed it. A caller who+ cannot be object-denied keeps orphan access, since orphaned history stays reachable for them."""- ref = api.resolve_subject(self.team.id, self.subject_type, self.subject_uuid)- if not ref.exists:- # Deleting the subject takes its denial with it: the orphan resolves to an empty name,- # and the denial set is rebuilt from the subjects that still exist, so neither can show- # the caller was allowed this one. Without that proof, only a caller who cannot be- # object-denied keeps orphan access.- if self._can_be_object_denied():- raise PermissionDenied("You don't have access to this table or view.")+ if not self._can_be_object_denied():return- if api.is_subject_denied(ref.name, self._denied_subject_names()):+ if not self._denial_context().readable.contains(self.subject_type, self.subject_uuid):raise PermissionDenied("You don't have access to this table or view.")@@ -323,6 +197,7 @@ _EDIT_DESCRIPTION = (class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewsets.ModelViewSet):"""CRUD for one subject's checks, plus the actions that run them and report on them."""+ DETAIL_VISIBILITY_ACTIONS = frozenset({"retrieve", "destroy"})QUERY_GATED_ACTIONS = frozenset({"list", "retrieve", "create", "update", "partial_update", "destroy", "run", "run_all", "runs", "health"})@@ -346,7 +221,18 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewsereturn querysetif not self._can_be_object_denied():return queryset- return queryset.exclude(id__in=self._denied_checks(list(queryset), self._denied_subject_names()))+ return queryset.exclude(id__in=self._hidden_check_ids(list(queryset)))++ def safely_get_object(self, queryset: QuerySet[DataQualityCheck]) -> DataQualityCheck:+ lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field+ check = get_object_or_404(queryset, **{self.lookup_field: self.kwargs[lookup_url_kwarg]})+ if (+ self.action in self.DETAIL_VISIBILITY_ACTIONS+ and self._can_be_object_denied()+ and check.id in self._hidden_check_ids([check])+ ):+ raise PermissionDenied("You don't have access to a table or view this check reads.")+ return checkdef get_serializer_context(self) -> dict:return {@@ -400,11 +286,15 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewse# relationships target or rewrites its custom SQL has to clear that subject too, before it# is saved and the worker starts running it.check = cast(DataQualityCheck, serializer.instance)+ redact_last_run = self._can_be_object_denied() and check.id in self._hidden_check_ids([check])data = serializer.validated_dataself._require_referenced_subject_access(data.get("check_type", check.check_type), data.get("config", check.config) or {})- serializer.save()+ updated_check = cast(DataQualityCheck, serializer.save())+ if redact_last_run:+ for field in _LAST_RUN_FIELDS:+ setattr(updated_check, field, None)def perform_destroy(self, instance: DataQualityCheck) -> None:api.soft_delete_check(instance)@@ -463,13 +353,12 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewse# The current definition gates the check itself; each run is then judged on the definition# it executed, so editing a check into a harmless one does not unlock what it used to read.self._require_referenced_subject_access(check.check_type, check.config)- runs = list(- DataQualityCheckRun.objects.for_team(self.team_id)- .filter(quality_check=check)- .select_related("quality_check")- .order_by("-created_at")[:_RECENT_RUNS_LIMIT]+ runs = self._readable_runs(+ DataQualityCheckRun.objects.for_team(self.team_id).filter(quality_check=check)+ ).select_related("quality_check")+ return Response(+ DataQualityCheckRunSerializer(list(runs.order_by("-created_at")[:_RECENT_RUNS_LIMIT]), many=True).data)- return Response(DataQualityCheckRunSerializer(self._readable_runs(runs), many=True).data)@extend_schema(description="Health rollup for this table or view, from the denormalized status of its checks.",@@ -482,7 +371,7 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewse# back to the database and count the withheld ones straight back in.checks = list(api.checks_for_subject(self.team_id, self.subject_type, self.subject_uuid).filter(enabled=True))if self._can_be_object_denied():- withheld = self._denied_checks(checks, self._denied_subject_names())+ withheld = self._hidden_check_ids(checks)checks = [check for check in checks if check.id not in withheld]return Response(SubjectHealthSerializer(@@ -552,12 +441,10 @@ class _BaseSuiteRunViewSet(return querysetif not self._can_be_object_denied():return queryset- # Only the runs behind the suites this parent serves, so answering for one subject does not- # walk the project's whole history.- runs = DataQualityCheckRun.objects.for_team(self.team_id).filter(- suite_run_id__in=queryset.order_by().values("id")+ context = self._denial_context()+ return queryset.exclude(api.unreadable_suites_q(context)).exclude(+ api.suites_backing_unreadable_runs_q(self.team_id, context))- return queryset.exclude(id__in=runs.filter(self._denied_definitions(runs)).values("suite_run_id"))@extend_schema(description="Every check execution in this suite run.",@@ -566,13 +453,10 @@ class _BaseSuiteRunViewSet(@action(methods=["GET"], detail=True, url_path="check_runs", pagination_class=None)def check_runs(self, request: Request, **kwargs) -> Response:suite_run = self.get_object()- runs = list(- DataQualityCheckRun.objects.for_team(self.team_id)- .filter(suite_run=suite_run)- .select_related("quality_check")- .order_by("-created_at")- )- return Response(DataQualityCheckRunSerializer(self._readable_runs(runs), many=True).data)+ runs = self._readable_runs(+ DataQualityCheckRun.objects.for_team(self.team_id).filter(suite_run=suite_run)+ ).select_related("quality_check")+ return Response(DataQualityCheckRunSerializer(list(runs.order_by("-created_at")), many=True).data)def _parent_id_parameter(name: str, description: str) -> Callable[[type], type]:@@ -648,7 +532,7 @@ class DataQualityCheckOverviewViewSet(queryset = super().filter_queryset(queryset)if not self._can_be_object_denied():return queryset- return queryset.exclude(id__in=self._denied_checks(list(queryset), self._denied_subject_names()))+ return queryset.exclude(id__in=self._hidden_check_ids(list(queryset)))@extend_schema(description="Health rollup for every table and view in the project that has checks.",@@ -714,46 +598,13 @@ class DataQualityRunViewSet(queryset = super().filter_queryset(queryset)if not self._can_be_object_denied():return queryset- runs = DataQualityCheckRun.objects.for_team(self.team_id)- denied_uuids = self._denied_subject_uuids()- if denied_uuids:- queryset = queryset.exclude(subject_uuid__in=denied_uuids).exclude(- id__in=runs.filter(subject_uuid__in=denied_uuids).values("suite_run_id")- )- # A run's declared subject is not the only one it read, so the same test the check routes- # apply to a definition has to reach the suites reporting on it.- return queryset.exclude(id__in=runs.filter(self._denied_definitions(runs)).values("suite_run_id"))-- def _denied_subject_uuids(self) -> set[UUID]:- """The ids of the subjects this caller is denied, as suite and check runs record them.-- Resolved from the subjects themselves rather than from the name denormalized onto a check,- so a subject renamed since its last run still matches its own denial.- """- denied = self._denied_subject_names()- checks = DataQualityCheck.objects.for_team(self.team_id).values_list(- "subject_type", "saved_query_id", "table_id", "subject_name"+ # A suite with runs is withheld when any of them touched a subject out of reach, the same+ # rule the check routes apply. A suite that swept nothing has no run to gate on, so its own+ # subject gates it directly -- which is the only path that reaches an empty suite.+ context = self._denial_context()+ return queryset.exclude(api.unreadable_suites_q(context)).exclude(+ api.suites_backing_unreadable_runs_q(self.team_id, context))- stamped = {- api.subject_identity(subject_type, saved_query_id or table_id): name- for subject_type, saved_query_id, table_id, name in checks- if saved_query_id or table_id- }- # A hard-deleted check leaves its runs behind with the FK nulled, so its subject would drop- # out of the set above while its suites still report on it.- stamped |= {- api.subject_identity(subject_type, subject_uuid): name- for subject_type, subject_uuid, name in DataQualityCheckRun.objects.for_team(self.team_id)- .filter(quality_check__isnull=True)- .values_list("subject_type", "subject_uuid", "subject_name")- .distinct()- }- current_names = api.resolve_subject_names(self.team_id, stamped.keys())- return {- UUID(identity.subject_uuid)- for identity, name in stamped.items()- if api.is_subject_denied(current_names.get(identity, name), denied)- }@extend_schema(description="Run the named checks now, or every enabled check in the project when none are named. "@@ -796,14 +647,10 @@ class DataQualityRunViewSet("""if not self._can_be_object_denied():return checks- denied = self._denied_subject_names()- current_names = api.resolve_subject_names(- self.team_id,- [api.subject_identity(check.subject_type, check.subject_uuid) for check in checks if check.subject_uuid],- )+ readable = self._denial_context().readableallowed = []for check in checks:- if api.is_subject_denied(_current_subject_name(check, current_names), denied):+ if not readable.contains(check.subject_type, check.subject_uuid):if named:raise PermissionDenied("You don't have access to a table or view this check reads.")continuediff --git a/products/data_quality/backend/temporal/activities/cleanup.py b/products/data_quality/backend/temporal/activities/cleanup.pyindex 2e2386576bc1..62666eac2df5 100644--- a/products/data_quality/backend/temporal/activities/cleanup.py+++ b/products/data_quality/backend/temporal/activities/cleanup.py@@ -1,6 +1,8 @@+from collections import defaultdictfrom datetime import UTC, datetime, timedelta+from typing import Any-from django.db.models import Exists, OuterRef, Q+from django.db.models import Exists, OuterRef, Q, QuerySetfrom asgiref.sync import sync_to_asyncfrom temporalio import activity@@ -18,6 +20,23 @@ CHECK_RUN_RETENTION_DAYS = 365SUITE_RUN_RETENTION_DAYS = 90STALE_SUITE_HOURS = 24STALE_SUITE_ERROR = "The workflow stopped without recording a result."+RETENTION_DELETE_BATCH_SIZE = 1_000+++def _delete_in_batches(queryset: "QuerySet[Any]") -> dict[str, int]:+ """Delete a queryset in id-batches, returning how many rows went per model label.++ One unbounded ``.delete()`` loads every matched row and everything that cascades with it into+ Django's collector. Each run drags its subject rows in, and each suite its check runs, so capping+ the parent rows per pass bounds that memory whatever the reverse relations pull along.+ """+ model = queryset.model+ totals: dict[str, int] = defaultdict(int)+ while ids := list(queryset.values_list("id", flat=True)[:RETENTION_DELETE_BATCH_SIZE]):+ _, by_model = model.objects.unscoped().filter(id__in=ids).delete()+ for label, count in by_model.items():+ totals[label] += count+ return totals@activity.defn@@ -37,19 +56,19 @@ def _cleanup() -> CleanupOutcome:)has_newer_run = runs.filter(quality_check_id=OuterRef("quality_check_id"), created_at__gt=OuterRef("created_at"))- runs_deleted, _ = (- runs.filter(created_at__lt=now - timedelta(days=CHECK_RUN_RETENTION_DAYS))- .filter(Q(quality_check_id__isnull=True) | Exists(has_newer_run))- .delete()+ expired_runs = runs.filter(created_at__lt=now - timedelta(days=CHECK_RUN_RETENTION_DAYS)).filter(+ Q(quality_check_id__isnull=True) | Exists(has_newer_run))+ # Count only the runs -- the subject rows that cascade with each one would otherwise inflate it.+ runs_deleted = _delete_in_batches(expired_runs).get(DataQualityCheckRun._meta.label, 0)backs_a_run = DataQualityCheckRun.objects.unscoped().filter(suite_run_id=OuterRef("id"))- suites_deleted, _ = (+ expired_suites = (DataQualitySuiteRun.objects.unscoped().filter(created_at__lt=now - timedelta(days=SUITE_RUN_RETENTION_DAYS)).filter(~Exists(backs_a_run))- .delete())+ suites_deleted = _delete_in_batches(expired_suites).get(DataQualitySuiteRun._meta.label, 0)stale_failed = (DataQualitySuiteRun.objects.unscoped()diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.pyindex 22f3d66fc064..3f6e9f84077b 100644--- a/products/data_quality/backend/tests/test_api.py+++ b/products/data_quality/backend/tests/test_api.py@@ -15,6 +15,7 @@ from posthog.constants import AvailableFeaturefrom products.access_control.backend.models.access_control import AccessControlfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.data_quality.backend.facade import apifrom products.data_quality.backend.facade.enums import CheckRunStatus, CheckSeverity, CheckType, SubjectTypefrom products.data_quality.backend.logic import checks as checks_logicfrom products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun@@ -579,8 +580,8 @@ class TestDataQualityCheckAPI(APIBaseTest):config=reads_orders,fingerprint=uuid4().hex,)- DataQualityCheckRun.objects.for_team(self.team.id).create(- team=self.team,+ api.record_check_run(+ self.team.id,suite_run=DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual"),quality_check=check,subject_type=SubjectType.VIEW,@@ -594,6 +595,12 @@ class TestDataQualityCheckAPI(APIBaseTest):failed_row_count=3,compiled_query="SELECT * FROM orders",)+ ran_at = now()+ DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id).update(+ last_status=CheckRunStatus.FAILED,+ last_run_at=ran_at,+ last_succeeded_at=ran_at,+ )self._deny_the_view()url = f"{self._checks_url(allowed.id)}/{check.id}"@@ -601,8 +608,15 @@ class TestDataQualityCheckAPI(APIBaseTest):history = self.client.get(f"{url}/runs/")assert edited.status_code == status.HTTP_200_OK, edited.json()+ assert edited.json()["last_status"] is None+ assert edited.json()["last_run_at"] is None+ assert edited.json()["last_succeeded_at"] is Noneassert history.status_code == status.HTTP_200_OKassert history.json() == []+ check.refresh_from_db()+ assert check.last_status == CheckRunStatus.FAILED+ assert check.last_run_at == ran_at+ assert check.last_succeeded_at == ran_atdef test_accepted_values_are_stored_as_the_column_holds_them(self) -> None:# The editor can only send strings. Whether the coercion is wired into the create path at all@@ -747,8 +761,8 @@ class TestDataQualityCheckAPI(APIBaseTest):config=config,fingerprint=uuid4().hex,)- DataQualityCheckRun.objects.for_team(self.team.id).create(- team=self.team,+ api.record_check_run(+ self.team.id,suite_run=suite,quality_check=check,subject_type=SubjectType.VIEW,@@ -842,8 +856,8 @@ class TestDataQualityCheckAPI(APIBaseTest):suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=allowed.id)- DataQualityCheckRun.objects.for_team(self.team.id).create(- team=self.team,+ api.record_check_run(+ self.team.id,suite_run=suite,quality_check=check,subject_type=SubjectType.VIEW,@@ -878,8 +892,8 @@ class TestDataQualityCheckAPI(APIBaseTest):suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=allowed.id)- DataQualityCheckRun.objects.for_team(self.team.id).create(- team=self.team,+ api.record_check_run(+ self.team.id,suite_run=suite,subject_type=SubjectType.VIEW,subject_uuid=allowed.id,@@ -908,8 +922,8 @@ class TestDataQualityCheckAPI(APIBaseTest):suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=allowed.id)- DataQualityCheckRun.objects.for_team(self.team.id).create(- team=self.team,+ api.record_check_run(+ self.team.id,suite_run=suite,subject_type=SubjectType.VIEW,subject_uuid=allowed.id,@@ -928,6 +942,78 @@ class TestDataQualityCheckAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert [row["check_type"] for row in response.json()] == [CheckType.CUSTOM_SQL]+ def test_a_deleted_declared_subject_withholds_its_history_from_a_restricted_member(self) -> None:+ # Deleting a subject takes its denial with it, so nothing left can show the caller was+ # allowed it. The run, its suite, and the check all fall out until retention deletes them.+ temp = self._make_view("temp_orders")+ check = DataQualityCheck.objects.for_team(self.team.id).create(+ team=self.team,+ subject_type=SubjectType.VIEW,+ saved_query_id=temp.id,+ subject_name="temp_orders",+ check_type=CheckType.NOT_NULL,+ column_name="id",+ fingerprint=uuid4().hex,+ )+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=temp.id+ )+ api.record_check_run(+ self.team.id,+ suite_run=suite,+ quality_check=check,+ subject_type=SubjectType.VIEW,+ subject_uuid=temp.id,+ subject_name="temp_orders",+ check_type=CheckType.NOT_NULL,+ check_config={},+ referenced_subjects=[],+ check_fingerprint=check.fingerprint,+ status=CheckRunStatus.FAILED,+ failed_row_count=3,+ )+ self._deny_the_view()+ temp.delete()++ assert self.client.get(f"{self._checks_url(temp.id)}/").status_code == status.HTTP_403_FORBIDDEN+ assert self.client.get(f"{self._suite_runs_url(temp.id)}/").status_code == status.HTTP_403_FORBIDDEN++ def test_a_restricted_member_loses_an_orphaned_checks_row_from_the_project_list(self) -> None:+ # An orphan has no subject left to prove access against, so it fails closed for a member who+ # can be object-denied -- even when nothing is currently denied to them.+ temp = self._make_view("temp_orders")+ DataQualityCheck.objects.for_team(self.team.id).create(+ team=self.team,+ subject_type=SubjectType.VIEW,+ saved_query_id=temp.id,+ subject_name="temp_orders",+ check_type=CheckType.NOT_NULL,+ column_name="id",+ fingerprint=uuid4().hex,+ )+ self._deny_the_view()+ self.view.delete()+ temp.delete()++ listed = self.client.get(f"/api/projects/{self.team.id}/data_quality_checks/")++ assert listed.status_code == status.HTTP_200_OK, listed.json()+ assert listed.json()["results"] == []++ def test_a_failure_building_the_readable_set_refuses_rather_than_leaks(self) -> None:+ # The snapshot walks every saved query; one malformed definition must not 500 the surface,+ # and must not fall through to serving rows it could not authorize.+ self._create_check()+ self._deny_the_view()++ with patch(+ "products.data_quality.backend.logic.subject_access.readable_subjects",+ side_effect=RuntimeError("boom"),+ ):+ response = self.client.get(f"{self.url}/")++ assert response.status_code == status.HTTP_403_FORBIDDEN+@parameterized.expand([("run", lambda self, url, check: self.client.post(f"{url}/{check.id}/run/")),@@ -953,6 +1039,30 @@ class TestDataQualityCheckAPI(APIBaseTest):assert call(self, self._checks_url(allowed.id), check).status_code == status.HTTP_403_FORBIDDEN+ @parameterized.expand(+ [+ ("retrieve", lambda self, url, check: self.client.get(f"{url}/{check.id}/")),+ ("destroy", lambda self, url, check: self.client.delete(f"{url}/{check.id}/")),+ ]+ )+ def test_a_denied_referenced_subject_blocks_direct_detail_actions(self, _name, call) -> None:+ allowed = self._make_view("customers")+ check = DataQualityCheck.objects.for_team(self.team.id).create(+ team=self.team,+ subject_type=SubjectType.VIEW,+ saved_query_id=allowed.id,+ subject_name="customers",+ check_type=CheckType.CUSTOM_SQL,+ config={"query": "SELECT 1 FROM orders"},+ fingerprint=uuid4().hex,+ )+ self._deny_the_view()++ response = call(self, self._checks_url(allowed.id), check)++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id, deleted=False).exists()+@parameterized.expand([("create", lambda self, check: self.client.post(f"{self.url}/", self._payload(column_name="total"))),diff --git a/products/data_quality/backend/tests/test_cleanup.py b/products/data_quality/backend/tests/test_cleanup.pyindex f31afb64b2fc..73df40c4ade2 100644--- a/products/data_quality/backend/tests/test_cleanup.py+++ b/products/data_quality/backend/tests/test_cleanup.py@@ -2,6 +2,10 @@ from datetime import UTC, datetime, timedeltafrom uuid import uuid4from posthog.test.base import BaseTest+from unittest.mock import patch++from django.db import connection+from django.test.utils import CaptureQueriesContextfrom parameterized import parameterized@@ -21,6 +25,8 @@ from products.data_quality.backend.temporal.activities.cleanup import (_cleanup,)+BATCH_SIZE = "products.data_quality.backend.temporal.activities.cleanup.RETENTION_DELETE_BATCH_SIZE"+class TestRetentionSweep(BaseTest):def setUp(self) -> None:@@ -94,6 +100,30 @@ class TestRetentionSweep(BaseTest):assert surviving == {newest.id}assert aged.id not in surviving+ def test_expired_runs_are_deleted_one_batch_at_a_time(self) -> None:+ recent = self._run()+ [self._run(age_days=CHECK_RUN_RETENTION_DAYS + 1) for _ in range(3)]++ with patch(BATCH_SIZE, 1), CaptureQueriesContext(connection) as queries:+ outcome = _cleanup()++ assert outcome.check_runs_deleted == 3+ assert set(DataQualityCheckRun.objects.unscoped().values_list("id", flat=True)) == {recent.id}+ run_delete = f'DELETE FROM "{DataQualityCheckRun._meta.db_table}"'+ assert sum(run_delete in query["sql"] for query in queries.captured_queries) == 3++ def test_expired_suites_are_deleted_one_batch_at_a_time(self) -> None:+ for _ in range(3):+ self._suite(age_days=SUITE_RUN_RETENTION_DAYS + 1)++ with patch(BATCH_SIZE, 1), CaptureQueriesContext(connection) as queries:+ outcome = _cleanup()++ assert outcome.suite_runs_deleted == 3+ assert not DataQualitySuiteRun.objects.unscoped().exists()+ suite_delete = f'DELETE FROM "{DataQualitySuiteRun._meta.db_table}"'+ assert sum(suite_delete in query["sql"] for query in queries.captured_queries) == 3+def test_an_aged_run_whose_check_is_gone_ages_out_unconditionally(self) -> None:orphan = self._run(age_days=CHECK_RUN_RETENTION_DAYS + 1, quality_check=None)diff --git a/products/data_quality/backend/tests/test_information_schema.py b/products/data_quality/backend/tests/test_information_schema.pyindex ca6168e752a6..b02b880173a4 100644--- a/products/data_quality/backend/tests/test_information_schema.py+++ b/products/data_quality/backend/tests/test_information_schema.py@@ -15,8 +15,10 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.models.team import Teamfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.data_quality.backend.facade.api import record_check_runfrom products.data_quality.backend.facade.enums import CheckRunStatus, CheckSeverity, CheckType, SubjectTypefrom products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from products.warehouse_sources.backend.facade.models import DataWarehouseTabledef _fail_queries_for_table(table_name: str):@@ -36,7 +38,13 @@ class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):)flag_patch.start()self.addCleanup(flag_patch.stop)- self.subject_uuid = uuid4()+ self.subject = self._view("orders")+ self.subject_uuid = self.subject.id++ def _view(self, name: str) -> DataWarehouseSavedQuery:+ return DataWarehouseSavedQuery.objects.create(+ team=self.team, name=name, query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )def _context(self, denied_tables: set[str] | None = None) -> HogQLContext:database = Database.create_for(team=self.team, user=self.user)@@ -60,7 +68,6 @@ class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):def _run_for(self, check: DataQualityCheck, **kwargs) -> DataQualityCheckRun:suite_run = DataQualitySuiteRun.objects.for_team(check.team_id).create(team=check.team, trigger="manual")defaults = {- "team": check.team,"quality_check": check,"suite_run": suite_run,"subject_type": check.subject_type,@@ -71,7 +78,7 @@ class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):"status": CheckRunStatus.FAILED,"failed_row_count": 4,}- return DataQualityCheckRun.objects.for_team(check.team_id).create(**{**defaults, **kwargs})+ return record_check_run(check.team_id, **{**defaults, **kwargs})def _query(self, sql: str, context: HogQLContext | None = None) -> list:return execute_hogql_query(sql, team=self.team, context=context or self._context()).results@@ -161,9 +168,9 @@ class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):])def test_a_denied_subject_is_hidden_from_every_data_quality_table(self, _name: str, sql: str) -> None:- denied = self._check(subject_name="orders", saved_query_id=uuid4())+ denied = self._check(subject_name="orders")self._run_for(denied)- allowed = self._check(subject_name="customers", saved_query_id=uuid4(), column_name="id")+ allowed = self._check(subject_name="customers", saved_query_id=self._view("customers").id, column_name="id")self._run_for(allowed)rows = self._query(sql, context=self._context(denied_tables={"orders"}))@@ -181,10 +188,7 @@ class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):def test_a_denied_subject_renamed_since_its_last_run_stays_hidden(self, _name: str, sql: str) -> None:# The name on the check is only rewritten when the check runs, so matching denial against it# serves the subject's rows for the whole window between a rename and the next run.- renamed = DataWarehouseSavedQuery.objects.create(- team=self.team, name="orders", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}- )- stale = self._check(subject_name="orders_legacy", saved_query_id=renamed.id)+ stale = self._check(subject_name="orders_legacy")self._run_for(stale)rows = self._query(sql, context=self._context(denied_tables={"orders"}))@@ -203,7 +207,7 @@ class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):# answers questions about the rows behind it.reader = self._check(subject_name="customers",- saved_query_id=uuid4(),+ saved_query_id=self._view("customers").id,check_type=CheckType.CUSTOM_SQL,column_name="",config={"query": "SELECT 1 FROM orders"},@@ -224,14 +228,12 @@ class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):# A check row is not only a definition: last_status is the verdict of its last run, over# whatever that run read. Once the subject it read is deleted and its name taken by something# the caller may read, the definition stops naming anything denied while the verdict remains.- original = DataWarehouseSavedQuery.objects.create(- team=self.team, name="orders_original", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}- )+ original = self._view("orders_original")original_id = original.idoriginal.delete()reader = self._check(subject_name="customers",- saved_query_id=self.subject_uuid,+ saved_query_id=self._view("customers").id,check_type=CheckType.CUSTOM_SQL,column_name="",config={"query": "SELECT 1 FROM orders"},@@ -251,14 +253,12 @@ class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):# Deleting a warehouse object frees its name for anyone to take. Matched by the names in its# definition, the run that read the original would be served here the moment something the# caller can read answers to that name -- with its failed-row count over the original's rows.- original = DataWarehouseSavedQuery.objects.create(- team=self.team, name="orders_original", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}- )+ original = self._view("orders_original")original_id = original.idoriginal.delete()reader = self._check(subject_name="customers",- saved_query_id=uuid4(),+ saved_query_id=self._view("customers").id,check_type=CheckType.CUSTOM_SQL,column_name="",config={"query": "SELECT 1 FROM orders"},@@ -277,6 +277,104 @@ class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):assert rows == []+ def test_a_backing_table_reference_stays_hidden_after_its_view_is_renamed(self) -> None:+ referenced_view = self._view("customers")+ backing_table = DataWarehouseTable.objects.create(+ team=self.team,+ name=referenced_view.name,+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern=f"s3://bucket/{referenced_view.folder_path}/{referenced_view.normalized_name}",+ )+ referenced_view.table = backing_table+ referenced_view.is_materialized = True+ referenced_view.save(update_fields=["table", "is_materialized"])+ check = self._check(+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT 1 FROM customers"},+ )+ self._run_for(+ check,+ check_config=check.config,+ referenced_subjects=[{"subject_type": str(SubjectType.TABLE), "subject_uuid": str(backing_table.id)}],+ )+ referenced_view.name = "customers_v2"+ referenced_view.save(update_fields=["name"])++ rows = self._query(+ "SELECT subject_name FROM system.information_schema.data_quality_check_runs",+ context=self._context(denied_tables={"customers_v2"}),+ )++ assert rows == []++ @parameterized.expand(+ [+ ("non_referencing", CheckType.NOT_NULL, {}, ["orders"]),+ ("referencing", CheckType.CUSTOM_SQL, {"query": "SELECT 1 FROM customers"}, []),+ ]+ )+ def test_a_run_predating_pinned_references_is_judged_by_its_type(+ self, _name: str, check_type: str, config: dict, expected: list[str]+ ) -> None:+ # Nothing backfills the references of a run recorded before they were pinned, so a null column+ # cannot be read as "touched nothing". A type that cannot reach past its own subject read only+ # the subject already authorized here; one that can is withheld.+ check = self._check(check_type=check_type, column_name="", config=config)+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual")+ DataQualityCheckRun.objects.for_team(self.team.id).create(+ team=self.team,+ quality_check=check,+ suite_run=suite_run,+ subject_type=SubjectType.VIEW,+ subject_uuid=self.subject_uuid,+ subject_name="orders",+ check_type=check_type,+ check_fingerprint=check.fingerprint,+ status=CheckRunStatus.FAILED,+ referenced_subjects=None,+ )++ rows = self._query(+ "SELECT subject_name FROM system.information_schema.data_quality_check_runs",+ context=self._context(denied_tables={"secrets"}),+ )++ assert [name for (name,) in rows] == expected++ def test_a_run_whose_declared_subject_was_deleted_is_withheld_from_a_restricted_member(self) -> None:+ # Deleting a subject takes its denial with it, so nothing left can show the caller was allowed+ # it. Hidden until retention deletes the history, rather than served on the strength of a name+ # anyone can now claim.+ temp = self._view("temp_orders")+ check = self._check(subject_name="temp_orders", saved_query_id=temp.id)+ self._run_for(check)+ temp.delete()++ rows = self._query(+ "SELECT subject_name FROM system.information_schema.data_quality_check_runs",+ context=self._context(denied_tables={"secrets"}),+ )++ assert rows == []++ def test_a_run_referencing_an_unknown_subject_type_is_withheld(self) -> None:+ # A future subject kind recorded before this gate learns it matches no readable branch, so it+ # is contained in nothing and the run falls out -- the fail-closed answer, not the reverse.+ check = self._check(check_type=CheckType.CUSTOM_SQL, column_name="", config={"query": "SELECT 1"})+ self._run_for(+ check,+ check_type=CheckType.CUSTOM_SQL,+ referenced_subjects=[{"subject_type": "dashboard", "subject_uuid": str(self.subject_uuid)}],+ )++ rows = self._query(+ "SELECT subject_name FROM system.information_schema.data_quality_check_runs",+ context=self._context(denied_tables={"secrets"}),+ )++ assert rows == []+def test_the_tables_are_absent_when_the_catalog_flag_is_off(self) -> None:with patch("products.data_quality.backend.facade.flags.is_data_quality_checks_enabled", return_value=False):listing = self._query(diff --git a/products/data_quality/backend/tests/test_notifications.py b/products/data_quality/backend/tests/test_notifications.pyindex 06cc70857bec..ca181e6ee015 100644--- a/products/data_quality/backend/tests/test_notifications.py+++ b/products/data_quality/backend/tests/test_notifications.py@@ -224,6 +224,19 @@ class TestDataQualityNotifications(BaseTest):assert self.user.id in resolvedassert blocked.id not in resolved+ def test_a_relationship_target_keeps_its_name_for_notification_filtering(self) -> None:+ check = self._check(+ check_type=CheckType.RELATIONSHIPS,+ column_name="customer_id",+ config={+ "to_subject_type": SubjectType.VIEW,+ "to_subject_uuid": str(self.view.id),+ "to_column": "id",+ },+ )++ assert referenced_subject_names(self.team.id, check.check_type, check.config) == ["orders"]+def test_members_denied_a_referenced_subject_do_not_get_the_blocked_materialization_count(self) -> None:# The blocked-materialization body counts the checks that failed, and one of them reads a# second view, so the count is an oracle over that view too. A member allowed the view beingdiff --git a/products/data_quality/backend/tests/test_runner.py b/products/data_quality/backend/tests/test_runner.pyindex 5fa6bbefc11d..b1bef748f3d7 100644--- a/products/data_quality/backend/tests/test_runner.py+++ b/products/data_quality/backend/tests/test_runner.py@@ -20,6 +20,7 @@ from products.data_quality.backend.facade.enums import ()from products.data_quality.backend.logic.runner import run_checkfrom products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from products.warehouse_sources.backend.facade.models import DataWarehouseTableRUNNER_QUERY = "products.data_quality.backend.logic.runner.execute_hogql_query"@@ -283,6 +284,15 @@ class TestCheckRunner(BaseTest):target = DataWarehouseSavedQuery.objects.create(team=self.team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"})+ backing_table = DataWarehouseTable.objects.create(+ team=self.team,+ name=target.name,+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern=f"s3://bucket/{target.folder_path}/{target.normalized_name}",+ )+ target.table = backing_table+ target.is_materialized = True+ target.save(update_fields=["table", "is_materialized"])is_custom_sql = check_type == CheckType.CUSTOM_SQLcheck = self._check(check_type=check_type,@@ -298,6 +308,11 @@ class TestCheckRunner(BaseTest):run = DataQualityCheckRun.objects.for_team(self.team.id).get(quality_check=check)assert run.referenced_subjects == [{"subject_type": SubjectType.VIEW, "subject_uuid": str(target.id)}]+ # The gate asks whether each entry is contained in the caller's readable set, and an entry+ # missing a key is contained in more than it should be. Exactly these two keys, both strings.+ entry = run.referenced_subjects[0]+ assert set(entry) == {"subject_type", "subject_uuid"}+ assert all(isinstance(value, str) for value in entry.values())@parameterized.expand([("custom_sql", CheckType.CUSTOM_SQL), ("relationships", CheckType.RELATIONSHIPS)])def test_an_automated_referencing_check_without_an_author_errors_without_running(diff --git a/products/data_quality/backend/tests/test_runs_api.py b/products/data_quality/backend/tests/test_runs_api.pyindex 5acebb3dc927..a75f8786f7ff 100644--- a/products/data_quality/backend/tests/test_runs_api.py+++ b/products/data_quality/backend/tests/test_runs_api.py@@ -15,7 +15,7 @@ from products.access_control.backend.models.access_control import AccessControlfrom products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Nodefrom products.data_quality.backend.facade import apifrom products.data_quality.backend.facade.enums import CheckRunStatus, CheckType, SubjectStatus, SubjectType-from products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from products.data_quality.backend.models import DataQualityCheck, DataQualitySuiteRunfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -40,6 +40,18 @@ class TestDataQualityRunAPI(APIBaseTest):team=self.team, name=name, query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"})+ def _materialize(self, view: DataWarehouseSavedQuery) -> DataWarehouseTable:+ backing_table = DataWarehouseTable.objects.create(+ team=self.team,+ name=view.name,+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern=f"s3://bucket/{view.folder_path}/{view.normalized_name}",+ )+ view.table = backing_table+ view.is_materialized = True+ view.save(update_fields=["table", "is_materialized"])+ return backing_table+def _check(self, view: DataWarehouseSavedQuery, **overrides) -> DataQualityCheck:return DataQualityCheck.objects.for_team(self.team.id).create(**{@@ -171,13 +183,17 @@ class TestDataQualityRunAPI(APIBaseTest):assert self.client.post(self.url, {}, format="json").status_code == status.HTTP_403_FORBIDDENassert self.client.get(self.url).status_code == status.HTTP_403_FORBIDDEN- def test_history_serves_the_sweeps_the_per_subject_surfaces_hide(self) -> None:- # The nested suite-run lists filter on subject_uuid, so a multi-subject sweep is only- # readable here.+ @parameterized.expand([("unrestricted_member", False), ("restricted_member", True)])+ def test_history_serves_the_sweeps_the_per_subject_surfaces_hide(self, _name: str, restricted: bool) -> None:+ # The nested suite-run lists filter on subject_uuid, so a multi-subject sweep is only readable+ # here. A sweep records no subject of its own, so the subject gate must skip it rather than+ # read the empty column as a subject nobody may see.sweep = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual")scoped = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="materialization", subject_type=SubjectType.VIEW, subject_uuid=self.orders.id)+ if restricted:+ self._deny(self._make_view("secrets"))listed = self.client.get(self.url)@@ -216,6 +232,30 @@ class TestDataQualityRunAPI(APIBaseTest):assert [row["id"] for row in listed.json()["results"]] == []assert self.client.get(f"{self.url}{suite_run.id}/").status_code == status.HTTP_404_NOT_FOUND+ def test_history_withholds_a_backing_table_reference_after_its_view_is_renamed(self) -> None:+ backing_table = self._materialize(self.orders)+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual")+ api.record_check_run(+ self.team.id,+ suite_run=suite_run,+ subject_type=SubjectType.VIEW,+ subject_uuid=self.customers.id,+ subject_name="customers",+ check_type=CheckType.CUSTOM_SQL,+ check_config={"query": "SELECT 1 FROM orders"},+ referenced_subjects=[{"subject_type": str(SubjectType.TABLE), "subject_uuid": str(backing_table.id)}],+ check_fingerprint=uuid4().hex,+ status=CheckRunStatus.FAILED,+ )+ self.orders.name = "orders_v2"+ self.orders.save(update_fields=["name"])+ self._deny(self.orders)++ listed = self.client.get(self.url)++ assert listed.json()["results"] == []+ assert self.client.get(f"{self.url}{suite_run.id}/").status_code == status.HTTP_404_NOT_FOUND+def test_history_withholds_a_suite_whose_subject_was_recreated_under_the_same_name(self) -> None:# Deleting "orders" frees its name, so a member can create their own and make the name resolve# for them again. Matched by name, the suite reporting on the run that read the original would@@ -231,11 +271,25 @@ class TestDataQualityRunAPI(APIBaseTest):assert [row["id"] for row in listed.json()["results"]] == []assert self.client.get(f"{self.url}{suite_run.id}/").status_code == status.HTTP_404_NOT_FOUND+ def test_history_withholds_a_suite_whose_run_declared_a_recreated_denied_subject(self) -> None:+ # A run's own subject was deleted and its name taken by a denied object. The suite reporting+ # on it still carries counters over the original's rows, so the freed name being reused by+ # something denied has to withhold it -- matched by the name the run stamped, not its id.+ temp = self._make_view("temp_orders")+ suite_run = self._sweep_covering(temp)+ temp.delete()+ self._deny(self._make_view("temp_orders"))++ listed = self.client.get(self.url)++ assert [row["id"] for row in listed.json()["results"]] == []+ assert self.client.get(f"{self.url}{suite_run.id}/").status_code == status.HTTP_404_NOT_FOUND+def _suite_reading(self, read: DataWarehouseSavedQuery) -> DataQualitySuiteRun:"""A suite whose one run sits on the allowed "customers" but read another subject."""suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual")- DataQualityCheckRun.objects.for_team(self.team.id).create(- team=self.team,+ api.record_check_run(+ self.team.id,suite_run=suite_run,subject_type=SubjectType.VIEW,subject_uuid=self.customers.id,@@ -251,8 +305,8 @@ class TestDataQualityRunAPI(APIBaseTest):def _sweep_covering(self, view: DataWarehouseSavedQuery) -> DataQualitySuiteRun:"""A multi-subject sweep whose counters include one check run against this view."""suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual")- DataQualityCheckRun.objects.for_team(self.team.id).create(- team=self.team,+ api.record_check_run(+ self.team.id,suite_run=suite_run,subject_type=SubjectType.VIEW,subject_uuid=view.id,@@ -303,6 +357,24 @@ class TestDataQualityRunAPI(APIBaseTest):assert listed.json()["results"] == []assert health.json() == []+ def test_the_overview_fails_closed_when_a_relationship_target_was_deleted(self) -> None:+ self._check(+ self.customers,+ check_type=CheckType.RELATIONSHIPS,+ column_name="customer_id",+ config={+ "to_subject_type": SubjectType.VIEW,+ "to_subject_uuid": str(self.orders.id),+ "to_column": "id",+ },+ )+ self.orders.delete()+ self._deny(self._make_view("secrets"))++ listed = self.client.get(self.checks_url)++ assert listed.json()["results"] == []+def test_the_overview_hides_a_check_whose_last_run_read_a_recreated_subject(self) -> None:# Deleting the denied "orders" empties the denial set and frees its name, so the config now# names something the member may read. The status beside it is still the verdict of a run@@ -314,8 +386,8 @@ class TestDataQualityRunAPI(APIBaseTest):config={"query": "SELECT 1 FROM orders"},last_status=CheckRunStatus.FAILED,)- DataQualityCheckRun.objects.for_team(self.team.id).create(- team=self.team,+ api.record_check_run(+ self.team.id,suite_run=DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual"),quality_check=reader,subject_type=SubjectType.VIEW,diff --git a/products/data_quality/backend/tests/test_subjects.py b/products/data_quality/backend/tests/test_subjects.pyindex b31451a6ee1f..250f6be5fe54 100644--- a/products/data_quality/backend/tests/test_subjects.py+++ b/products/data_quality/backend/tests/test_subjects.py@@ -4,12 +4,18 @@ from posthog.test.base import BaseTestfrom parameterized import parameterized+from posthog.hogql.database.database import Database+from posthog.models.team import Team+from products.data_modeling.backend.facade import api as data_modeling_facadefrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_quality.backend.facade.enums import SubjectType+from products.data_quality.backend.logic.subject_access import readable_subjectsfrom products.data_quality.backend.logic.subjects import resolve_subjectfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourceclass TestSubjectResolver(BaseTest):@@ -54,3 +60,77 @@ class TestSubjectResolver(BaseTest):other_team = Team.objects.create(organization=self.organization, name="Other team")assert not resolve_subject(other_team.id, SubjectType.TABLE, table.id).exists+++class TestReadableSubjectSnapshot(BaseTest):+ def _table(+ self, name: str, *, source: ExternalDataSource | None = None, url_pattern: str = "s3://bucket/x"+ ) -> DataWarehouseTable:+ return DataWarehouseTable.objects.create(+ team=self.team,+ name=name,+ format=DataWarehouseTable.TableFormat.Parquet,+ columns={"id": {"clickhouse": "Int64", "hogql": "integer"}},+ external_data_source=source,+ url_pattern=url_pattern,+ )++ def _materialized_view(self, name: str = "orders") -> tuple[DataWarehouseSavedQuery, DataWarehouseTable]:+ view = DataWarehouseSavedQuery.objects.create(+ team=self.team, name=name, query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ backing_table = self._table(+ f"{name}_backing", url_pattern=f"s3://bucket/{view.folder_path}/{view.normalized_name}"+ )+ view.table = backing_table+ view.is_materialized = True+ view.save(update_fields=["table", "is_materialized"])+ return view, backing_table++ def test_snapshot_exclusions_match_the_database_catalog(self) -> None:+ _view, backing_table = self._materialized_view()+ direct_source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="direct_source",+ connection_id="direct_connection",+ source_type=ExternalDataSourceType.POSTGRES,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ )+ direct_table = self._table("direct_customers", source=direct_source)+ plain_table = self._table("plain_customers")+ tables = (backing_table, direct_table, plain_table)++ database = Database.create_for(team=self.team, bypass_warehouse_access_control=True)+ catalog_excluded = {table.id for table in tables if not database.has_table(table.name)}+ readable = readable_subjects(self.team.id, set())+ snapshot_excluded = {table.id for table in tables} - readable.table_ids++ assert catalog_excluded == {backing_table.id, direct_table.id}+ assert snapshot_excluded == catalog_excluded++ def test_a_soft_deleted_views_backing_table_stays_out_of_the_snapshot(self) -> None:+ view, backing_table = self._materialized_view()+ view.deleted = True+ view.save(update_fields=["deleted"])++ readable = readable_subjects(self.team.id, set())++ assert backing_table.id not in readable.table_ids++ def test_backing_table_map_includes_soft_deleted_views_in_one_query(self) -> None:+ view, backing_table = self._materialized_view()+ view.deleted = True+ view.save(update_fields=["deleted"])+ source_table = self._table("source_orders")+ DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="source_orders_view",+ query={"kind": "HogQLQuery", "query": "SELECT * FROM source_orders"},+ table=source_table,+ is_materialized=True,+ )++ with self.assertNumQueries(1):+ backing_tables = data_modeling_facade.backing_table_ids_by_saved_query(self.team.id)++ assert backing_tables == {backing_table.id: view.id}diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex e283b4efa205..028fc6ab7fef 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -70,6 +70,7 @@ __all__ = ["get_table","get_queryable_table","resolve_object_by_name",+ "direct_access_table_ids","list_tables_for_source","list_jobs_for_source","list_column_statistics",@@ -356,18 +357,22 @@ def resolve_object_by_name(team_id: int, name: str) -> contracts.WarehouseObjectreturn contracts.WarehouseObjectRef(kind=kind, id=resolved.id)-def queryable_table_names(team_id: int, table_ids: Collection[UUID]) -> dict[UUID, str]:- """The current name of each table that is still queryable. One query; anything gone is absent.-- The bulk form of ``get_queryable_table`` for a caller that only needs names, so authorizing a- page of stored table references costs one query rather than one per reference.- """- if not table_ids:- return {}- rows = _DataWarehouseTable.raw_objects.queryable().filter(team_id=team_id, id__in=list(table_ids))+def all_queryable_table_names(team_id: int) -> dict[UUID, str]:+ """The current name of every table in this team that is still queryable. One query."""+ rows = _DataWarehouseTable.raw_objects.queryable().filter(team_id=team_id)return dict(rows.values_list("id", "name"))+def direct_access_table_ids(team_id: int) -> set[UUID]:+ """The queryable tables belonging to direct-access sources in this team. One query."""+ rows = (+ _DataWarehouseTable.raw_objects.queryable()+ .filter(team_id=team_id, external_data_source__access_method=_ExternalDataSource.AccessMethod.DIRECT)+ .values_list("id", flat=True)+ )+ return set(rows)++def list_tables_for_source(source_id: UUID, team_id: int) -> list[contracts.DataWarehouseTable]:qs = _DataWarehouseTable.objects.filter(team_id=team_id, external_data_source_id=source_id).exclude(deleted=True)return [_to_table(t) for t in qs]