Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(data-quality): stop building a warehouse database per notification recipient (#100980)

Thiago Salvatore85fbabc1354b
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 8cc0268b4b04..0430d5f75aec 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -662,6 +662,17 @@ def _compute_system_table_access_decision(
return user_access_control, denied
+def system_table_denials(
+ team: Team, user: User, user_access_control: Optional[UserAccessControl] = None
+) -> frozenset[str]:
+ """The bare names of the ``system.*`` tables this user may not read.
+
+ Runs the access-control and entitlement checks that ``create_for`` would run, and nothing else,
+ so a caller that only needs the answer does not pay for a whole database build.
+ """
+ return frozenset(_compute_system_table_access_decision(team, user, user_access_control)[1])
+
+
class Database(BaseModel):
model_config = ConfigDict(extra="allow")
diff --git a/products/data_quality/backend/logic/notifications.py b/products/data_quality/backend/logic/notifications.py
index 543376e4e78f..4f5d3856c7af 100644
--- a/products/data_quality/backend/logic/notifications.py
+++ b/products/data_quality/backend/logic/notifications.py
@@ -29,10 +29,12 @@ from ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun
from .checks import checks_for_subject
from .flags import is_data_quality_checks_enabled_for_team_id
from .subject_access import (
- DenialContext,
+ DenialContextKey,
+ ReferenceGate,
SubjectMetadata,
caller_denial_context,
can_be_object_denied,
+ denial_context_key,
referenced_subject_names,
referencing_check_types,
subject_metadata,
@@ -80,6 +82,7 @@ class _WarehouseSubjectResolver(RecipientsResolver):
# database build the referenced-subject gate runs) so a single failing check doesn't rebuild
# it -- and its membership, role, and access-control lookups -- once per pass.
self._access: dict[int, UserAccessControl] = {}
+ self._gates: dict[DenialContextKey, ReferenceGate] = {}
self._subject_metadata: SubjectMetadata | None = None
def _access_of(self, user: User) -> UserAccessControl:
@@ -130,12 +133,7 @@ class _WarehouseSubjectResolver(RecipientsResolver):
return True
if self._references_unknown and can_be_object_denied(access):
return False
- context = self._denial_context_of(user)
- if self._executed_references and not all(
- context.readable.contains(ref["subject_type"], ref["subject_uuid"]) for ref in self._executed_references
- ):
- return False
- return not context.matcher.matches(self._referenced_names)
+ return self._gate_of(user).admits(self._executed_references, self._referenced_names)
def _has_object_access(self, access: UserAccessControl) -> bool:
object_id = UUID(self._subject_uuid)
@@ -146,10 +144,17 @@ class _WarehouseSubjectResolver(RecipientsResolver):
)
return object_id in allowed_ids
- def _denial_context_of(self, user: User) -> DenialContext:
- if self._subject_metadata is None:
- self._subject_metadata = subject_metadata(self._team.id)
- return caller_denial_context(self._team, user, self._access_of(user), metadata=self._subject_metadata)
+ def _gate_of(self, user: User) -> ReferenceGate:
+ access = self._access_of(user)
+ key = denial_context_key(self._team, user, access)
+ gate = self._gates.get(key)
+ if gate is None:
+ if self._subject_metadata is None:
+ self._subject_metadata = subject_metadata(self._team.id)
+ context = caller_denial_context(self._team, user, access, metadata=self._subject_metadata)
+ gate = ReferenceGate(readable=context.readable, matcher=context.matcher)
+ self._gates[key] = gate
+ return gate
def notify_check_started_failing(
diff --git a/products/data_quality/backend/logic/subject_access.py b/products/data_quality/backend/logic/subject_access.py
index 42a2f2323e82..fb02d5b55180 100644
--- a/products/data_quality/backend/logic/subject_access.py
+++ b/products/data_quality/backend/logic/subject_access.py
@@ -20,7 +20,7 @@ from uuid import UUID
from django.db.models import Exists, OuterRef, Q, QuerySet
-from posthog.hogql.database.database import Database
+from posthog.hogql.database.database import Database, system_table_denials
from posthog.hogql.database.schema.information_schema import DeniedTableMatcher
from posthog.dataclasses import frozen
@@ -115,6 +115,63 @@ class DenialContext:
object.__setattr__(self, "matcher", DeniedTableMatcher(self.denied))
+@frozen
+class ReferenceGate:
+ """Decides whether one person may be told a check failed.
+
+ A check can read tables other than the one it is defined on: a ``custom_sql`` check reads
+ whatever its query selects, and a ``relationships`` check reads the table it points at. The
+ failure count in the notification therefore says something about every one of those tables, so
+ a person who may not read one of them must not get the notification.
+
+ Holds the two things that answer this: the tables, views and metrics the person may read, and
+ a matcher for the table names they are denied.
+
+ Both come from the person's :class:`DenialContextKey` and from nothing else, so one gate can
+ serve every person whose key is equal. The :class:`DenialContext` it is built from cannot be
+ shared that way, because that also holds the HogQL database built for one specific person.
+ """
+
+ readable: ReadableSubjects
+ matcher: DeniedTableMatcher = field(compare=False)
+
+ def admits(self, executed_references: Sequence[dict[str, str]], names: Sequence[str]) -> bool:
+ readable_references = all(
+ self.readable.contains(ref[_SUBJECT_TYPE_KEY], ref[_SUBJECT_UUID_KEY]) for ref in executed_references
+ )
+ if not readable_references:
+ return False
+ return not self.matcher.matches(names)
+
+
+@frozen
+class DenialContextKey:
+ """What one person is allowed to read, reduced to something a cache can key on.
+
+ Working out which table names a person is denied is expensive, because it builds a HogQL
+ database for them. These four values are the only things about the person that the answer
+ depends on, so two people on the same team with equal keys are denied exactly the same names.
+
+ A surface that has to check hundreds of people can therefore resolve one :class:`DenialContext`
+ per distinct key instead of one per person.
+ """
+
+ allowed_table_ids: frozenset[UUID]
+ allowed_view_ids: frozenset[UUID]
+ can_read_catalog: bool
+ denied_system_tables: frozenset[str]
+
+
+def denial_context_key(team: "Team", user: "User", user_access_control: "UserAccessControl") -> DenialContextKey:
+ """Reads the key for one person. Runs a few Postgres queries and builds no HogQL database."""
+ return DenialContextKey(
+ allowed_table_ids=warehouse_facade.allowed_table_ids(team.id, user_access_control),
+ allowed_view_ids=data_modeling_facade.allowed_saved_query_ids(team.id, user_access_control),
+ can_read_catalog=user_access_control.check_access_level_for_resource("data_catalog", "viewer"),
+ denied_system_tables=system_table_denials(team, user, user_access_control),
+ )
+
+
@frozen
class SubjectMetadata:
table_names: dict[UUID, str]
diff --git a/products/data_quality/backend/temporal/activities/materialization_gate.py b/products/data_quality/backend/temporal/activities/materialization_gate.py
index 26f1037bc911..b5a89c7e4a42 100644
--- a/products/data_quality/backend/temporal/activities/materialization_gate.py
+++ b/products/data_quality/backend/temporal/activities/materialization_gate.py
@@ -1,6 +1,7 @@
-from asgiref.sync import sync_to_async
from temporalio import activity
+from posthog.sync import database_sync_to_async_pool
+
from ...facade.contracts import MATERIALIZATION_GATE_ACTIVITY_NAME
from ...logic.triggers import materialization_checks_needed
from ..contracts import MaterializationGateInputs
@@ -14,4 +15,4 @@ async def materialization_gate_activity(inputs: MaterializationGateInputs) -> bo
workflow may not touch. Asking before the start keeps a flag-disabled org from paying for a
child workflow and an empty suite row on every materialization.
"""
- return await sync_to_async(materialization_checks_needed)(inputs.team_id, inputs.node_ids)
+ return await database_sync_to_async_pool(materialization_checks_needed)(inputs.team_id, inputs.node_ids)
diff --git a/products/data_quality/backend/temporal/activities/run_check_batch.py b/products/data_quality/backend/temporal/activities/run_check_batch.py
index 8d0ee87a1b3f..ccafd966abd4 100644
--- a/products/data_quality/backend/temporal/activities/run_check_batch.py
+++ b/products/data_quality/backend/temporal/activities/run_check_batch.py
@@ -2,10 +2,10 @@ from collections import Counter
from django.db.models import QuerySet
-from asgiref.sync import sync_to_async
from temporalio import activity
from posthog.models.team import Team
+from posthog.sync import database_sync_to_async_pool
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger
@@ -21,7 +21,7 @@ LOGGER = get_logger(__name__)
@activity.defn
async def run_check_batch_activity(inputs: RunCheckBatchInputs) -> BatchOutcome:
async with Heartbeater():
- return await sync_to_async(_run_batch)(inputs)
+ return await database_sync_to_async_pool(_run_batch)(inputs)
def _record_unaudited_batch(
diff --git a/products/data_quality/backend/tests/test_notifications.py b/products/data_quality/backend/tests/test_notifications.py
index 1410ba66ba1e..3ced6f06ac31 100644
--- a/products/data_quality/backend/tests/test_notifications.py
+++ b/products/data_quality/backend/tests/test_notifications.py
@@ -10,6 +10,8 @@ from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
+from posthog.hogql.database.database import Database
+
from posthog.constants import AvailableFeature
from posthog.models import OrganizationMembership, User
@@ -331,20 +333,11 @@ class TestDataQualityNotifications(BaseTest):
assert self.user.id in resolved
assert blocked.id not in resolved
- def _deny_view_for_member(self, view, member: User) -> None:
- # Deny one member object-level access to a view the way the HogQL database sees it, so
- # denied_subject_names() picks it up -- the same setup the REST run-history tests use.
+ def _enable_access_controls(self) -> 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(view.id),
- organization_member=OrganizationMembership.objects.get(organization=self.organization, user=member),
- access_level="none",
- )
flag = patch(
"posthog.hogql.database.database.feature_enabled_or_false",
side_effect=lambda name, *a, **k: name == "hogql-warehouse-access-control",
@@ -353,6 +346,18 @@ class TestDataQualityNotifications(BaseTest):
self.addCleanup(flag.stop)
cache.clear()
+ def _deny_view_for_member(self, view, member: User) -> None:
+ # Deny one member object-level access to a view the way the HogQL database sees it, so
+ # denied_subject_names() picks it up -- the same setup the REST run-history tests use.
+ self._enable_access_controls()
+ AccessControl.objects.create(
+ team=self.team,
+ resource="warehouse_view",
+ resource_id=str(view.id),
+ organization_member=OrganizationMembership.objects.get(organization=self.organization, user=member),
+ access_level="none",
+ )
+
@parameterized.expand(
[
("custom_sql", CheckType.CUSTOM_SQL, "", {"query": "SELECT 1 FROM orders"}, True),
@@ -394,6 +399,53 @@ class TestDataQualityNotifications(BaseTest):
assert self.user.id in resolved
assert blocked.id not in resolved
+ def _custom_sql_check_reading_orders(self) -> DataQualityCheck:
+ customers = DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}
+ )
+ return self._check(
+ saved_query_id=customers.id,
+ subject_name="customers",
+ check_type=CheckType.CUSTOM_SQL,
+ column_name="",
+ config={"query": "SELECT 1 FROM orders"},
+ )
+
+ def test_members_with_equal_access_share_one_warehouse_database_build(self) -> None:
+ denied_first = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ denied_second = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ allowed_first = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ allowed_second = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ self._deny_view_for_member(self.view, denied_first)
+ self._deny_view_for_member(self.view, denied_second)
+ check = self._custom_sql_check_reading_orders()
+
+ with patch.object(Database, "create_for", side_effect=Database.create_for) as build:
+ resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)
+
+ assert build.call_count == 2
+ assert {allowed_first.id, allowed_second.id, self.user.id} <= set(resolved)
+ assert denied_first.id not in resolved
+ assert denied_second.id not in resolved
+
+ def test_org_admins_share_one_warehouse_database_build(self) -> None:
+ first_admin = User.objects.create_and_join(
+ self.organization, "[email protected]", "password", level=OrganizationMembership.Level.ADMIN
+ )
+ second_admin = User.objects.create_and_join(
+ self.organization, "[email protected]", "password", level=OrganizationMembership.Level.ADMIN
+ )
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save(update_fields=["level"])
+ self._enable_access_controls()
+ check = self._custom_sql_check_reading_orders()
+
+ with patch.object(Database, "create_for", side_effect=Database.create_for) as build:
+ resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)
+
+ assert build.call_count == 1
+ assert {first_admin.id, second_admin.id, self.user.id} <= set(resolved)
+
def test_a_relationship_target_keeps_its_name_for_notification_filtering(self) -> None:
check = self._check(
check_type=CheckType.RELATIONSHIPS,