:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-quality): build the caller's HogQL database only when a definition verdict needs it (#101254)
Thiago Salvatore40ea5c2f9547
diff --git a/products/data_quality/backend/logic/exceptions.py b/products/data_quality/backend/logic/exceptions.pyindex 3423f58cbd24..44979cdc0f67 100644--- a/products/data_quality/backend/logic/exceptions.py+++ b/products/data_quality/backend/logic/exceptions.py@@ -18,3 +18,14 @@ class CheckNameConflict(APIException):status_code = status.HTTP_409_CONFLICTdefault_detail = "A check with this name already exists in this project."default_code = "check_name_conflict"+++class SubjectAccessUnverifiable(APIException):+ """A 403 for a caller whose access to a table or view could not be established.++ ``detail`` must stay a plain string, for the same reason as above.+ """++ status_code = status.HTTP_403_FORBIDDEN+ default_detail = "Could not verify your access to this table or view."+ default_code = "subject_access_unverifiable"diff --git a/products/data_quality/backend/logic/permissions.py b/products/data_quality/backend/logic/permissions.pyindex 480c72d4564b..386543853fd4 100644--- a/products/data_quality/backend/logic/permissions.py+++ b/products/data_quality/backend/logic/permissions.py@@ -82,7 +82,9 @@ def _scope_allows(scopes: Collection[str] | None, resource: str, write: bool) ->def restrict_subject_types(context: DenialContext, allowed: Collection[SubjectType]) -> DenialContext:denied = set(context.denied)if SubjectType.TABLE not in allowed:+ # Both spellings, because a query can write either and the matcher compares leaf names.denied.update(context.metadata.table_names.values())+ denied.update(context.metadata.table_keys.values())if SubjectType.VIEW not in allowed:denied.update(context.metadata.view_names.values())return replace(diff --git a/products/data_quality/backend/logic/subject_access.py b/products/data_quality/backend/logic/subject_access.pyindex 19e81d32dea0..98afe857e70c 100644--- a/products/data_quality/backend/logic/subject_access.py+++ b/products/data_quality/backend/logic/subject_access.py@@ -12,7 +12,7 @@ know is absent from that snapshot and therefore out of reach."""import json-from collections.abc import Collection, Sequence+from collections.abc import Callable, Collection, Sequencefrom dataclasses import fieldfrom functools import cachefrom itertools import batched@@ -37,6 +37,7 @@ from ..facade.enums import SubjectTypefrom ..models import DataQualityCheck, DataQualityCheckRunfrom .checks import latest_run_idsfrom .contracts import SubjectIdentity, SubjectRef+from .exceptions import SubjectAccessUnverifiablefrom .registry import all_specs, get_specfrom .spec import CheckTypeSpecfrom .subjects import resolve_metric_subjects, resolve_subject, resolve_subject_by_name@@ -99,18 +100,52 @@ class ReadableSubjects:return False+class DeferredDatabase:+ """The caller's HogQL database, built at most once and only if a verdict needs it.++ Only one question needs the whole HogQL name universe: whether a name a definition reads can be+ confirmed to resolve at all. Every other gate here is answered from identities and names, so a+ surface that asks none of them -- the run-history routes -- must not pay for a database holding+ every warehouse table of the team as a pydantic object.++ A plain class rather than a frozen dataclass, because it memoizes and :class:`DenialContext`+ stays frozen around it.+ """++ def __init__(self, build: Callable[[], Database]) -> None:+ self._build = build+ self._database: Database | None = None++ @classmethod+ def built(cls, database: Database) -> "DeferredDatabase":+ return cls(lambda: database)++ @classmethod+ def lazy(cls, build: Callable[[], Database]) -> "DeferredDatabase":+ return cls(build)++ def get(self) -> Database:+ if self._database is None:+ try:+ self._database = self._build()+ except Exception as err:+ capture_exception(err)+ raise SubjectAccessUnverifiable+ return self._database++@frozenclass 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.+ ones a definition asks, and ``database`` is the caller's own HogQL database -- deferred, so it+ is built only where a verdict needs it and a surface that has one already never builds a second."""readable: ReadableSubjectsdenied: set[str]- database: Database+ database: DeferredDatabasemetadata: "SubjectMetadata"matcher: DeniedTableMatcher = field(init=False, repr=False, compare=False)@@ -203,17 +238,22 @@ def reference_gate(@frozenclass SubjectMetadata:+ """The team's live subjects by id. ``table_keys`` is the dotted form a query writes."""+table_names: dict[UUID, str]+ table_keys: dict[UUID, str]view_names: dict[UUID, str]metrics: tuple[MetricSummary, ...]def subject_metadata(team_id: int) -> SubjectMetadata:- tables = warehouse_facade.all_queryable_table_names(team_id)+ tables = warehouse_facade.all_queryable_table_keys(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))+ included = {table_id: names for table_id, names in tables.items() if table_id not in excluded_table_ids}return SubjectMetadata(- table_names={table_id: name for table_id, name in tables.items() if table_id not in excluded_table_ids},+ table_names={table_id: names.row_name for table_id, names in included.items()},+ table_keys={table_id: names.queryable_key for table_id, names in included.items()},view_names={UUID(view_id): name for view_id, name in data_modeling_facade.all_saved_query_names(team_id).items()},@@ -246,16 +286,41 @@ def readable_subjects()+def unreachable_subject_names(+ team_id: int, user_access_control: Optional["UserAccessControl"], metadata: SubjectMetadata+) -> set[str]:+ """Every name this caller cannot reach, in both spellings a query can write.++ A source table answers to its row name and to its dotted key, and the gate that reads this+ matches leaf names, so recording only one of the two would let the other spelling through. No+ access-control context means nothing is reachable, which is how a service token fails closed.+ """+ allowed_tables = (+ warehouse_facade.allowed_table_ids(team_id, user_access_control)+ if user_access_control is not None+ else frozenset()+ )+ allowed_views = (+ data_modeling_facade.allowed_saved_query_ids(team_id, user_access_control)+ if user_access_control is not None+ else frozenset()+ )+ denied = {+ spelling+ for identifier, name in metadata.table_names.items()+ if identifier not in allowed_tables+ for spelling in (name, metadata.table_keys.get(identifier, name))+ }+ denied.update(name for identifier, name in metadata.view_names.items() if identifier not in allowed_views)+ return denied++def denial_context(team_id: int, database: Database, *, metadata: SubjectMetadata | None = None) -> DenialContext:"""The caller's denial state, from a HogQL database that has already been built for them."""metadata = metadata if metadata is not None else subject_metadata(team_id)- denied = set(database._denied_tables)access = database.user_access_control+ denied = set(database._denied_tables) | unreachable_subject_names(team_id, access, metadata)can_read_catalog = access is not None and access.check_access_level_for_resource("data_catalog", "viewer")- allowed_tables = warehouse_facade.allowed_table_ids(team_id, access) if access is not None else frozenset()- allowed_views = data_modeling_facade.allowed_saved_query_ids(team_id, access) if access is not None else frozenset()- denied.update(name for identifier, name in metadata.table_names.items() if identifier not in allowed_tables)- denied.update(name for identifier, name in metadata.view_names.items() if identifier not in allowed_views)return DenialContext(readable=readable_subjects(team_id,@@ -264,7 +329,7 @@ def denial_context(team_id: int, database: Database, *, metadata: SubjectMetadatmetadata=metadata,),denied=denied,- database=database,+ database=DeferredDatabase.built(database),metadata=metadata,)@@ -272,13 +337,38 @@ def denial_context(team_id: int, database: Database, *, metadata: SubjectMetadatdef caller_denial_context(team: "Team",user: "User",- user_access_control: Optional["UserAccessControl"] = None,+ user_access_control: "UserAccessControl",*,metadata: SubjectMetadata | None = 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), metadata=metadata+ """The caller's denial state, read from their grants. Defers the HogQL database build.++ The denial set a database would compute for this caller is the same object access check over the+ same objects, so it is derived here instead. The build is kept behind+ :class:`DeferredDatabase` for the one verdict that needs the whole name universe.+ """+ try:+ metadata = metadata if metadata is not None else subject_metadata(team.id)+ denied = set(system_table_denials(team, user, user_access_control))+ denied.update(unreachable_subject_names(team.id, user_access_control, metadata))+ readable = readable_subjects(+ team.id,+ denied,+ can_read_catalog=user_access_control.check_access_level_for_resource("data_catalog", "viewer"),+ metadata=metadata,+ )+ except Exception as err:+ # The snapshot walks every saved query; one malformed definition must not 500 the surface,+ # and failing open would leak denied subjects.+ capture_exception(err)+ raise SubjectAccessUnverifiable+ return DenialContext(+ readable=readable,+ denied=denied,+ database=DeferredDatabase.lazy(+ lambda: Database.create_for(team=team, user=user, user_access_control=user_access_control)+ ),+ metadata=metadata,)@@ -443,19 +533,23 @@ def definition_reads_unreadable_subject(refs.related_subject.subject_type, refs.related_subject.subject_uuid):return True+ if not refs.names:+ return Falseif context.matcher.matches(refs.names):return True- return bool(unconfirmable_subject_names(refs.names, context.database))+ return bool(unconfirmable_subject_names(refs.names, context.database.get()))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)}+ """Every referenced name the caller's own database does not expose.++ A name is absent from that database for two reasons, and neither proves access. It was deleted,+ which takes its denial with it: the name leaves both the database 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. Or the caller is denied it, which the denial set does not always carry --+ the backing table of a soft-deleted saved query is denied in the database and absent from the+ set. Both are reported and the caller fails them closed."""+ return {name for name in names if not database.has_table(name)}# A check type reads beyond its declared subject only if it overrides one of these hooks: adiff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.pyindex fbaf0488101c..7e20000a71b9 100644--- a/products/data_quality/backend/presentation/views.py+++ b/products/data_quality/backend/presentation/views.py@@ -28,7 +28,6 @@ from rest_framework.views import APIViewfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action-from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team, Userfrom posthog.permissions import APIScopePermission, TeamMemberAccessPermission, get_authenticator_scopesfrom posthog.rate_limit import HogQLQueryThrottle@@ -187,20 +186,14 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):"""cached = getattr(self, "_denial_context_cache", None)if cached is None:- try:- cached = api.restrict_subject_types(- api.caller_denial_context(- self.team,- cast(User, self.request.user),- user_access_control=self.user_access_control,- ),- self._authorized_subject_types(),- )- 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.")+ cached = api.restrict_subject_types(+ api.caller_denial_context(+ self.team,+ cast(User, self.request.user),+ user_access_control=self.user_access_control,+ ),+ self._authorized_subject_types(),+ )self._denial_context_cache = cachedreturn cacheddiff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.pyindex 1cfd579c15a3..3eb083cad8df 100644--- a/products/data_quality/backend/tests/test_api.py+++ b/products/data_quality/backend/tests/test_api.py@@ -13,6 +13,8 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIRequestFactory+from posthog.hogql.database.database import Database+from posthog.constants import AvailableFeaturefrom posthog.models.activity_logging.activity_log import ActivityLog, Detail, log_activity@@ -28,6 +30,7 @@ from products.data_quality.backend.models import DataQualityCheck, DataQualityChfrom products.data_quality.backend.presentation.serializers import DataQualitySuiteRunSerializerfrom products.data_quality.backend.presentation.views import SavedQueryCheckViewSetfrom products.warehouse_sources.backend.models.credential import DataWarehouseCredential+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTableif TYPE_CHECKING:@@ -1300,14 +1303,17 @@ class TestDataQualityCheckAPI(APIBaseTest):def _deny_the_view(self) -> None:# Deny the default member object-level access to the "orders" view, the way the HogQL# database sees it -- so denied_subject_names() picks it up and the endpoint hides it.+ self._deny_object("warehouse_view", str(self.view.id))++ def _deny_object(self, resource: str, resource_id: str) -> None:self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}]self.organization.save(update_fields=["available_product_features"])AccessControl.objects.create(team=self.team,- resource="warehouse_view",- resource_id=str(self.view.id),+ resource=resource,+ resource_id=resource_id,organization_member=self.organization_membership,access_level="none",)@@ -1390,6 +1396,99 @@ class TestDataQualityCheckAPI(APIBaseTest):assert response.status_code == status.HTTP_403_FORBIDDENassert DataQualityCheck.objects.for_team(self.team.id).count() == 0+ def test_a_denied_source_table_stays_denied_under_the_key_a_query_writes(self) -> None:+ allowed = self._make_view("customers")+ charges = DataWarehouseTable.objects.create(+ team=self.team,+ name="stripe_charges",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://bucket/stripe_charges",+ external_data_source=ExternalDataSource.objects.create(team=self.team, source_type="Stripe"),+ )+ reads_charges = self._payload(+ check_type=CheckType.CUSTOM_SQL, column_name="", config={"query": "SELECT 1 FROM stripe.charges"}+ )+ created = self.client.post(f"{self._checks_url(allowed.id)}/", reads_charges)+ assert created.status_code == status.HTTP_201_CREATED, created.json()+ self._deny_object("warehouse_table", str(charges.id))++ with patch.object(Database, "create_for", side_effect=Database.create_for) as build:+ listed = self.client.get(f"{self._checks_url(allowed.id)}/")+ recreated = self.client.post(f"{self._checks_url(allowed.id)}/", reads_charges)++ build.assert_not_called()+ assert listed.status_code == status.HTTP_200_OK, listed.json()+ assert listed.json()["results"] == []+ assert recreated.status_code == status.HTTP_403_FORBIDDEN++ @parameterized.expand(+ [+ ("a_definition_that_names_a_table", "SELECT {index} FROM customers", 1),+ ("no_names_at_all", "SELECT {index}", 0),+ ]+ )+ def test_a_listing_builds_the_callers_warehouse_database_at_most_once(+ self, _name: str, query: str, expected_builds: int+ ) -> None:+ allowed = self._make_view("customers")+ for index in range(3):+ self._create_check(+ url=self._checks_url(allowed.id),+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": query.format(index=index)},+ )+ self._deny_the_view()++ with patch.object(Database, "create_for", side_effect=Database.create_for) as build:+ listed = self.client.get(f"{self._checks_url(allowed.id)}/")++ assert listed.status_code == status.HTTP_200_OK, listed.json()+ assert len(listed.json()["results"]) == 3+ assert build.call_count == expected_builds++ def test_the_backing_table_of_a_deleted_view_is_denied_like_any_other(self) -> None:+ allowed = self._make_view("customers")+ orphaned = self._make_view("daily_orders")+ backing_table = DataWarehouseTable.objects.create(+ team=self.team,+ name=orphaned.name,+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern=f"s3://bucket/{orphaned.folder_path}/{orphaned.normalized_name}",+ )+ DataWarehouseSavedQuery.objects.filter(id=orphaned.id).update(+ table=backing_table, is_materialized=True, deleted=True+ )+ reads_backing_table = self._payload(+ check_type=CheckType.CUSTOM_SQL, column_name="", config={"query": f"SELECT 1 FROM {backing_table.name}"}+ )+ created = self.client.post(f"{self._checks_url(allowed.id)}/", reads_backing_table)+ assert created.status_code == status.HTTP_201_CREATED, created.json()+ self._deny_object("warehouse_table", str(backing_table.id))++ listed = self.client.get(f"{self._checks_url(allowed.id)}/")+ recreated = self.client.post(f"{self._checks_url(allowed.id)}/", reads_backing_table)++ assert listed.status_code == status.HTTP_200_OK, listed.json()+ assert listed.json()["results"] == []+ assert recreated.status_code == status.HTTP_403_FORBIDDEN++ def test_a_database_build_that_fails_refuses_rather_than_500s(self) -> None:+ allowed = self._make_view("customers")+ self._create_check(+ url=self._checks_url(allowed.id),+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT 1 FROM customers"},+ )+ self._deny_the_view()++ with patch.object(Database, "create_for", side_effect=RuntimeError("a saved query will not parse")):+ response = self.client.get(f"{self._checks_url(allowed.id)}/")++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert response.json()["detail"] == "Could not verify your access to this table or view."+@parameterized.expand([("patch",), ("put",)])def test_editing_a_check_to_read_a_denied_subject_writes_nothing(self, method: str) -> None:# The stored definition cleared the denial; the candidate one has to clear it too, or an editdiff --git a/products/data_quality/backend/tests/test_runs_api.py b/products/data_quality/backend/tests/test_runs_api.pyindex 942e2fd61fad..e12b5b174059 100644--- a/products/data_quality/backend/tests/test_runs_api.py+++ b/products/data_quality/backend/tests/test_runs_api.py@@ -10,6 +10,8 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from posthog.hogql.database.database import Database+from posthog.constants import AvailableFeaturefrom posthog.models import OrganizationMembership, PersonalAPIKeyfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication@@ -616,6 +618,21 @@ class TestDataQualityRunAPI(APIBaseTest):assert self.client.get(f"{self.url}{denied.id}/").status_code == status.HTTP_404_NOT_FOUNDassert self.client.get(f"{self.url}{sweep.id}/").status_code == status.HTTP_404_NOT_FOUND+ def test_history_never_builds_the_callers_warehouse_database(self) -> None:+ self._check(self.orders)+ denied = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger="materialization", subject_type=SubjectType.VIEW, subject_uuid=self.orders.id+ )+ self._deny_orders()++ with patch.object(Database, "create_for", side_effect=Database.create_for) as build:+ listed = self.client.get(self.url)+ retrieved = self.client.get(f"{self.url}{denied.id}/")++ build.assert_not_called()+ assert [row["id"] for row in listed.json()["results"]] == []+ assert retrieved.status_code == status.HTTP_404_NOT_FOUND+def test_history_withholds_a_suite_whose_run_read_a_denied_subject(self) -> None:# The run sits on the allowed subject, so its own uuid clears the filter. What it read is in# the identities it pinned, and the counters report on those rows too.diff --git a/products/data_quality/backend/tests/test_subject_access.py b/products/data_quality/backend/tests/test_subject_access.pyindex ef39441b0196..07f66fed0e97 100644--- a/products/data_quality/backend/tests/test_subject_access.py+++ b/products/data_quality/backend/tests/test_subject_access.py@@ -6,6 +6,8 @@ from posthog.test.base import BaseTestfrom unittest.mock import patchfrom django.core.cache import cache+from django.db import connection+from django.test.utils import CaptureQueriesContextfrom parameterized import parameterized@@ -25,9 +27,11 @@ from products.data_catalog.backend.facade.models import Metricfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_quality.backend.facade.enums import SubjectTypefrom products.data_quality.backend.logic.checks import upsert_check-from products.data_quality.backend.logic.permissions import writable_subjects+from products.data_quality.backend.logic.exceptions import SubjectAccessUnverifiable+from products.data_quality.backend.logic.permissions import restrict_subject_types, writable_subjectsfrom products.data_quality.backend.logic.runner import run_checkfrom products.data_quality.backend.logic.subject_access import (+ DeferredDatabase,DenialContext,definition_reads_unreadable_subject,denial_context,@@ -70,11 +74,10 @@ class TestMetricSubjectAccess(BaseTest):[("metric_table", {"revenue_rows"}, True), ("extra_table", {"thresholds"}, True), ("allowed", set(), False)])def test_composed_references_control_access(self, _name: str, denied: set[str], expected: bool) -> None:- database = Database.create_for(team=self.team, user=self.user)context = DenialContext(readable=readable_subjects(self.team.id, denied),denied=denied,- database=database,+ database=DeferredDatabase.built(Database.create_for(team=self.team, user=self.user)),metadata=subject_metadata(self.team.id),)assert (@@ -235,7 +238,7 @@ class TestMetricSubjectAccess(BaseTest):context = DenialContext(readable=readable,denied=denied,- database=Database.create_for(team=self.team, user=self.user),+ database=DeferredDatabase.built(Database.create_for(team=self.team, user=self.user)),metadata=subject_metadata(self.team.id),)assert (@@ -248,7 +251,7 @@ class TestMetricSubjectAccess(BaseTest):context = DenialContext(readable=readable_subjects(self.team.id, set()),denied=set(),- database=Database.create_for(team=self.team, user=self.user),+ database=DeferredDatabase.built(Database.create_for(team=self.team, user=self.user)),metadata=subject_metadata(self.team.id),)with self.assertNumQueries(4):@@ -257,6 +260,67 @@ class TestMetricSubjectAccess(BaseTest):with self.assertNumQueries(2):assert hidden_check_ids(self.team.id, [check] * 20, context) == {check.id}+ def test_a_database_build_that_fails_is_reported_as_unverifiable_access(self) -> None:+ def explode() -> Database:+ raise RuntimeError("a saved query will not parse")++ with self.assertRaises(SubjectAccessUnverifiable):+ DeferredDatabase.lazy(explode).get()++ def test_the_deferred_database_is_built_once_and_only_when_a_verdict_needs_it(self) -> None:+ builds = 0++ def build() -> Database:+ nonlocal builds+ builds += 1+ return Database.create_for(team=self.team, user=self.user)++ deferred = DeferredDatabase.lazy(build)+ assert builds == 0+ assert deferred.get() is deferred.get()+ assert builds == 1++ def test_reading_the_subject_snapshot_costs_the_same_however_many_source_tables_exist(self) -> None:+ source = ExternalDataSource.objects.create(team=self.team, source_type="Stripe")+ with CaptureQueriesContext(connection) as one_table:+ subject_metadata(self.team.id)+ for index in range(5):+ DataWarehouseTable.objects.create(+ team=self.team,+ name=f"stripe_charges_{index}",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern=f"s3://bucket/charges_{index}",+ external_data_source=source,+ )++ with CaptureQueriesContext(connection) as six_tables:+ metadata = subject_metadata(self.team.id)++ assert len(six_tables.captured_queries) == len(one_table.captured_queries)+ assert "stripe.charges_0" in metadata.table_keys.values()++ @parameterized.expand([("row_name", "stripe_charges"), ("queryable_key", "stripe.charges")])+ def test_scoping_tables_away_denies_every_name_a_query_can_write(self, _name: str, written_as: str) -> None:+ # A caller whose scopes reach views but not tables must not read a check that selects from a+ # source table, whichever of the table's two names the query writes.+ DataWarehouseTable.objects.create(+ team=self.team,+ name="stripe_charges",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://bucket/stripe_charges",+ external_data_source=ExternalDataSource.objects.create(team=self.team, source_type="Stripe"),+ )+ context = DenialContext(+ readable=readable_subjects(self.team.id, set()),+ denied=set(),+ database=DeferredDatabase.built(Database.create_for(team=self.team, user=self.user)),+ metadata=subject_metadata(self.team.id),+ )++ restricted = restrict_subject_types(context, [SubjectType.VIEW, SubjectType.METRIC])++ assert restricted.matcher.matches([written_as]) is True+def test_failed_composition_cannot_record_empty_references(self) -> None:assert pin_referenced_subjects(self.team.id, "custom_sql", {"query": "SELECT 1"}, subject=self.subject) is Nonediff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex 8014ff82c79c..a99e02090d21 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -371,6 +371,38 @@ def all_queryable_table_names(team_id: int) -> dict[UUID, str]:return dict(rows.values_list("id", "name"))+def all_queryable_table_keys(team_id: int) -> dict[UUID, contracts.TableNames]:+ """Every queryable table of this team, by id, under both the names it answers to. One query.++ A caller matching what a query read against what a person may reach has to know both spellings.+ """+ from posthog.hogql.database.database import ( # noqa: PLC0415 -- keeps HogQL off this module's import path+ get_data_warehouse_table_name,+ )++ rows = (+ _DataWarehouseTable.raw_objects.queryable()+ .filter(team_id=team_id)+ .select_related("external_data_source")+ .only(+ "id",+ "name",+ "external_data_source_id",+ "external_data_source__id",+ "external_data_source__access_method",+ "external_data_source__source_type",+ "external_data_source__prefix",+ )+ )+ return {+ table.id: contracts.TableNames(+ row_name=table.name,+ queryable_key=get_data_warehouse_table_name(table.external_data_source, table.name),+ )+ for table in rows+ }++def direct_access_table_ids(team_id: int) -> set[UUID]:"""The queryable tables belonging to direct-access sources in this team. One query."""rows = (diff --git a/products/warehouse_sources/backend/facade/contracts.py b/products/warehouse_sources/backend/facade/contracts.pyindex e5a89c81e86e..dd0676841049 100644--- a/products/warehouse_sources/backend/facade/contracts.py+++ b/products/warehouse_sources/backend/facade/contracts.py@@ -151,6 +151,19 @@ class TableSourceLocation:schema_id: UUID+@dataclass(frozen=True)+class TableNames:+ """The two names one warehouse table answers to.++ ``row_name`` is what the table row stores and a listing shows. ``queryable_key`` is what a+ query writes, which for a source table is the dotted form. They are equal for a direct-access+ source and for a table with no source.+ """++ row_name: str+ queryable_key: str++WAREHOUSE_OBJECT_TABLE = "table"WAREHOUSE_OBJECT_VIEW = "view"