: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-modeling): allow account system tables in materializations (#94475)
Arthur Moreira de Deus85c8571f2ff3
diff --git a/posthog/hogql/ACCESS_CONTROL.md b/posthog/hogql/ACCESS_CONTROL.mdindex 703fdc42c4b8..94fef3bba7af 100644--- a/posthog/hogql/ACCESS_CONTROL.md+++ b/posthog/hogql/ACCESS_CONTROL.md@@ -150,13 +150,15 @@ Without a user, warehouse access control denies every warehouse table and view,Cache warming runs as the insight's creator, on the assumption that their access is the one most viewers of that insight share.Warming without access control would more often end in a cache miss.-3. **Trusted internal job with no user at all:** pass `bypass_warehouse_access_control=True` explicitly. Used by materialization workflows (`posthog/temporal/data_modeling/`), insight cache warming, and ducklake compilation (`posthog/ducklake/client.py`). **Be very skeptical before adding a new bypass** — only do it when the job genuinely has no acting user and the output isn't served to a specific user with narrower access.+3. **Trusted internal job with no user at all:** pass `bypass_warehouse_access_control=True` explicitly. Materialization workflows (`posthog/temporal/data_modeling/`), insight cache warming, and ducklake compilation (`posthog/ducklake/client.py`) use this path. Add a bypass only when the job has no acting user and its output has a separate access boundary.```python-# Background materialization job — no user exists, bypass explicitly+# Background materialization job: no user exists, so bypass explicitly.execute_hogql_query(query=..., team=team, bypass_warehouse_access_control=True)```+Data Modeling materialized views are project-owned. Refreshes do not run as `created_by` and do not inherit account, ticket, or object-level access. Data Modeling passes `allowed_system_tables` to declassify approved system tables into warehouse data. The allowlist accepts exact table names and denies every other system table. Warehouse-view permissions protect the materialized result. Billing entitlements still apply, and only userless database builds can use the allowlist.+4. **Public dashboards / notebooks / shared insights:** the viewer is anonymous, so queries run as `SharedLinkUser` (`posthog/shared_link_user.py`, built in `SharingViewerPageViewSet`).`Database.create_for` doesn't restrict any warehouse tables or views for a shared-link viewer; the access gate is at publish time instead.Enabling sharing requires editor-level access to the resource, so only someone who already has access can publish it.diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 412024e2dfa9..62102e8f083c 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -7,7 +7,7 @@ import threadingimport dataclassesimport pickletoolsfrom collections import defaultdict-from collections.abc import Callable, Mapping, Sequence+from collections.abc import Callable, Collection, Mapping, Sequencefrom datetime import UTC, datetimefrom functools import cachefrom types import MappingProxyType@@ -265,6 +265,10 @@ type DatabaseSchemaTable = (logger = structlog.get_logger(__name__)+def is_reserved_system_name(name: str) -> bool:+ return name == "system" or name.startswith("system.")++# READ BEFORE EDITING:# --------------------# Do NOT add any new table to this, add them to the `posthog` table node.@@ -545,6 +549,7 @@ def _compute_system_table_access_decision(team: Team,user: Optional[User | SyntheticUser | SharedLinkUser],user_access_control: Optional[UserAccessControl] = None,+ allowed_system_tables: Collection[str] | None = None,) -> tuple[Optional[UserAccessControl], set[str]]:"""Decide which scoped system tables to hide, doing the access-control I/O here so the build phasecan apply the result without querying. Returns the warmed UserAccessControl (preloaded, so later@@ -561,6 +566,16 @@ def _compute_system_table_access_decision()scoped_tables = _scoped_system_tables()+ allowed_system_table_names = frozenset(allowed_system_tables or ())+ if allowed_system_table_names and (user is not None or user_access_control is not None):+ raise ValueError("allowed_system_tables is restricted to userless database creation")+ invalid_allowed_tables = allowed_system_table_names.difference(scoped_tables)+ if invalid_allowed_tables:+ invalid_names = ", ".join(sorted(invalid_allowed_tables))+ raise ValueError(+ f"allowed_system_tables must contain exact bare names of scoped system tables: {invalid_names}"+ )+# Applies to every principal below, admins included - an entitlement the organization does not# have cannot be granted by a role.unentitled = _unentitled_system_tables(team)@@ -568,9 +583,12 @@ def _compute_system_table_access_decision(# Anonymous or synthetic principal: keep only access-controlled tables its scopes cover (none for shared link / team token).if user is None or isinstance(user, SyntheticUser | SharedLinkUser):readable_scopes = user.readable_system_table_access_scopes() if user is not None else set()- return None, unentitled | {+ denied_by_access_control = {name for name, table in scoped_tables.items() if table.access_scope not in readable_scopes}+ if user is None:+ denied_by_access_control.difference_update(allowed_system_table_names)+ return None, unentitled | denied_by_access_controluser_access_control = user_access_control or UserAccessControl(user=user, team=team)@@ -1376,6 +1394,7 @@ class Database(BaseModel):bypass_warehouse_access_control: bool = False,build_postgres_foreign_keys: bool = True,trigger: str = "direct",+ allowed_system_tables: Collection[str] | None = None,) -> Database:if timings is None:timings = HogQLTimings()@@ -1391,6 +1410,7 @@ class Database(BaseModel):timings=timings,connection_id=connection_id,bypass_warehouse_access_control=bypass_warehouse_access_control,+ allowed_system_tables=allowed_system_tables,)with HOGQL_DATABASE_BUILD_DURATION_SECONDS.labels(phase="build_from_sources").time():return Database._build_from_sources(@@ -1448,6 +1468,7 @@ class Database(BaseModel):timings: HogQLTimings | None = None,connection_id: str | None = None,bypass_warehouse_access_control: bool = False,+ allowed_system_tables: Collection[str] | None = None,) -> HogQLDatabaseSources:"""Run every Postgres query / feature-flag check / external request needed to build thedatabase, returning a bundle that Database._build_from_sources turns into tables with no I/O."""@@ -1571,7 +1592,7 @@ class Database(BaseModel):# Pass the caller's user_access_control through: when already preloaded it's reused, so the# bulk access-control fetch happens once per run instead of once per database build.user_access_control, denied_system_table_names = _compute_system_table_access_decision(- team, user, user_access_control+ team, user, user_access_control, allowed_system_tables)is_hogql_warehouse_access_control_enabled = feature_enabled_or_false(@@ -1951,6 +1972,8 @@ class Database(BaseModel):with timings.measure("data_warehouse_saved_query", emit_span=True):for saved_query in sources.saved_queries:with timings.measure(f"saved_query_{saved_query.name}"):+ if is_reserved_system_name(saved_query.name):+ continueif (sources.is_hogql_warehouse_access_control_enabledand not sources.bypass_warehouse_access_control@@ -1970,6 +1993,8 @@ class Database(BaseModel):try:for endpoint_saved_query in sources.endpoint_saved_queries:with timings.measure(f"endpoint_saved_query_{endpoint_saved_query.name}"):+ if is_reserved_system_name(endpoint_saved_query.name):+ continue# Endpoint-origin saved queries are a separate list, so they're checked tooif (sources.is_hogql_warehouse_access_control_enableddiff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.pyindex b485fa5f756d..7b594bb2d39d 100644--- a/posthog/hogql/database/test/test_database.py+++ b/posthog/hogql/database/test/test_database.py@@ -2,6 +2,7 @@ import ioimport jsonimport pickleimport dataclasses+from collections.abc import Collectionfrom typing import Any, castimport pytest@@ -70,9 +71,13 @@ from posthog.models.group_type_mapping import invalidate_group_types_cachefrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.scoping import team_scopefrom posthog.models.team.team import Team+from posthog.models.user import Userfrom posthog.schema_enums import SessionTableVersion+from posthog.shared_link_user import SharedLinkUser+from posthog.synthetic_user import SyntheticUserfrom posthog.test.test_utils import create_group_type_mapping_without_created_at+from products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_tools.backend.models.expression import DataWarehouseExpressionfrom products.data_tools.backend.models.join import DataWarehouseJoin@@ -4116,8 +4121,13 @@ class TestDatabase(BaseTest, QueryMatchingTest):captured: dict = {}- def spy(team, user, user_access_control=None):- result = _compute_system_table_access_decision(team, user, user_access_control)+ def spy(+ team: Team,+ user: User | SyntheticUser | SharedLinkUser | None,+ user_access_control: UserAccessControl | None = None,+ allowed_system_tables: Collection[str] | None = None,+ ) -> tuple[UserAccessControl | None, set[str]]:+ result = _compute_system_table_access_decision(team, user, user_access_control, allowed_system_tables)captured["result"] = resultreturn result@@ -4138,8 +4148,13 @@ class TestDatabase(BaseTest, QueryMatchingTest):def test_create_for_with_real_user_uses_user_rbac(self):captured: dict = {}- def spy(team, user, user_access_control=None):- result = _compute_system_table_access_decision(team, user, user_access_control)+ def spy(+ team: Team,+ user: User | SyntheticUser | SharedLinkUser | None,+ user_access_control: UserAccessControl | None = None,+ allowed_system_tables: Collection[str] | None = None,+ ) -> tuple[UserAccessControl | None, set[str]]:+ result = _compute_system_table_access_decision(team, user, user_access_control, allowed_system_tables)captured["result"] = resultreturn result@@ -4153,6 +4168,65 @@ class TestDatabase(BaseTest, QueryMatchingTest):# A real user gets per-user access control computed rather than the anonymous all-deny path.assert user_access_control is not None+ def test_existing_saved_query_cannot_fill_denied_system_table_name(self) -> None:+ DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="system.accounts",+ query={"kind": "HogQLQuery", "query": "SELECT 1"},+ )++ database = Database.create_for(team=self.team)++ with pytest.raises(TableAccessDeniedError):+ database.get_table("system.accounts")++ def test_userless_system_table_allowlist_is_exact(self) -> None:+ database = Database.create_for(+ team=self.team,+ allowed_system_tables=frozenset({"accounts"}),+ )++ assert "system.accounts" in database.get_system_table_names()+ assert "system.feature_flags" not in database.get_system_table_names()+ with pytest.raises(TableAccessDeniedError):+ database.get_table("system.feature_flags")++ @parameterized.expand(+ [+ ("qualified", "system.accounts"),+ ("unscoped", "_account_tagged_items"),+ ("unknown", "not_a_system_table"),+ ]+ )+ def test_system_table_allowlist_rejects_invalid_names(self, _name: str, table_name: str) -> None:+ with pytest.raises(ValueError, match="exact bare names of scoped system tables"):+ Database.create_for(+ team=self.team,+ allowed_system_tables=frozenset({table_name}),+ )++ def test_system_table_allowlist_rejects_real_users(self) -> None:+ with pytest.raises(ValueError, match="restricted to userless database creation"):+ Database.create_for(+ team=self.team,+ user=self.user,+ allowed_system_tables=frozenset({"accounts"}),+ )++ def test_system_table_allowlist_does_not_override_cloud_entitlements(self) -> None:+ self.organization.available_product_features = []+ self.organization.save()++ with self.is_cloud(True):+ database = Database.create_for(+ team=self.team,+ allowed_system_tables=frozenset({"activity_logs"}),+ )++ assert "system.activity_logs" not in database.get_system_table_names()+ with pytest.raises(TableAccessDeniedError):+ database.get_table("system.activity_logs")+@parameterized.expand([# Admin/owner cases matter most: they short-circuit RBAC, so an entitlement check placeddiff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex 4b214dbff004..7ca722a65f4a 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -61,6 +61,7 @@ from products.data_modeling.backend.facade.api import ()from products.data_modeling.backend.facade.modeling import bounded_resolver_factory_for_viewfrom products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery, Node, NodeType+from products.data_modeling.backend.facade.system_tables import DATA_MODELING_ALLOWED_SYSTEM_TABLESfrom products.data_quality.backend.facade import api as data_quality_facadefrom products.data_quality.backend.facade.contracts import QUALITY_AUDIT_SKIP, QualityAuditModefrom products.data_warehouse.backend.facade.api import ensure_bucket_exists, get_s3_client@@ -553,7 +554,10 @@ async def hogql_table(# Userless materialization context; bypass warehouse HogQL access control so the model query# can resolve its source tables/views.context.database = await database_sync_to_async_pool(Database.create_for)(- team=team, modifiers=context.modifiers, bypass_warehouse_access_control=True+ team=team,+ modifiers=context.modifiers,+ bypass_warehouse_access_control=True,+ allowed_system_tables=DATA_MODELING_ALLOWED_SYSTEM_TABLES,)factory = bounded_resolver_factory_for_view(view_name)diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex c70971d09309..82f81df9c0f4 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -1734,6 +1734,34 @@ class TestHogqlTableModifiers:assert captured_sql is not None and expected_sql in captured_sql+ async def test_compiles_account_dependencies_without_a_user(self, ateam: Team) -> None:+ schema_fields: list[pa.Field[Any]] = [+ pa.field("id", pa.string()),+ pa.field("feature_request_count", pa.int64()),+ pa.field("email_thread_count", pa.int64()),+ ]+ client = _EmptyArrowClient(pa.schema(schema_fields))+ client.describe_body = b"id\tUUID\nfeature_request_count\tUInt64\nemail_thread_count\tUInt64\n"++ @contextlib.asynccontextmanager+ async def fake_get_client(**kwargs: Any) -> AsyncIterator[_EmptyArrowClient]:+ yield client++ query = """+ SELECT+ id,+ feature_requests.count AS feature_request_count,+ email_threads.count AS email_thread_count+ FROM system.accounts+ """+ with unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.materialize_view.get_clickhouse_client", fake_get_client+ ):+ batches = [batch async for batch in hogql_table(query, ateam, LOGGER.bind())]++ assert len(batches) == 1+ assert client.arrow_query is not None+class TestHogqlTableEmptyResults:async def test_zero_row_query_uses_the_initial_stream_schema(self, ateam):diff --git a/products/data_modeling/backend/facade/system_tables.py b/products/data_modeling/backend/facade/system_tables.pynew file mode 100644index 000000000000..222b228b6344--- /dev/null+++ b/products/data_modeling/backend/facade/system_tables.py@@ -0,0 +1,17 @@+DATA_MODELING_ALLOWED_SYSTEM_TABLES: frozenset[str] = frozenset(+ {+ "_account_channel_summaries",+ "_account_custom_property_values",+ "_account_custom_property_values_history",+ "_account_email_thread_links",+ "_account_email_threads",+ "_account_meetings",+ "account_relationship_definitions",+ "account_relationships",+ "accounts",+ "custom_property_definitions",+ "feature_request_account_links",+ "feature_requests",+ "support_tickets",+ }+)diff --git a/products/data_modeling/backend/logic/saved_query_dag_sync.py b/products/data_modeling/backend/logic/saved_query_dag_sync.pyindex 9c17d9518914..92c241ee9aec 100644--- a/products/data_modeling/backend/logic/saved_query_dag_sync.py+++ b/products/data_modeling/backend/logic/saved_query_dag_sync.py@@ -10,6 +10,7 @@ from posthog.hogql.database.models import SavedQuery as HogQLSavedQueryfrom posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehouseTablefrom posthog.hogql.errors import QueryError+from products.data_modeling.backend.facade.system_tables import DATA_MODELING_ALLOWED_SYSTEM_TABLESfrom products.data_modeling.backend.logic.node_suspension import clear_suspension_if_query_changedfrom products.data_modeling.backend.logic.schedule_reconcile import maybe_reconcile_dagfrom products.data_modeling.backend.models.dag import DAG, REVENUE_ANALYTICS_DAG_NAME@@ -241,7 +242,11 @@ def sync_saved_query_to_dag(# Internal DAG sync (no user); bypass warehouse HogQL access control so dependency resolution# sees every referenced table/view.if database is None:- database = Database.create_for(team=team, bypass_warehouse_access_control=True)+ database = Database.create_for(+ team=team,+ bypass_warehouse_access_control=True,+ allowed_system_tables=DATA_MODELING_ALLOWED_SYSTEM_TABLES,+ )# clear previous incoming edges, dependencies may have changedEdge.objects.filter(team=team, target=target).delete()diff --git a/products/data_modeling/backend/models/datawarehouse_managed_viewset.py b/products/data_modeling/backend/models/datawarehouse_managed_viewset.pyindex 021e6f8e52aa..ff98a9a0e746 100644--- a/products/data_modeling/backend/models/datawarehouse_managed_viewset.py+++ b/products/data_modeling/backend/models/datawarehouse_managed_viewset.py@@ -21,6 +21,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDTModel, sane_reprfrom products.data_modeling.backend.facade.managed_viewset_hooks import get_expected_views_provider+from products.data_modeling.backend.facade.system_tables import DATA_MODELING_ALLOWED_SYSTEM_TABLESfrom products.data_modeling.backend.models.dag import DAGfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_modeling.backend.models.node import Node@@ -102,7 +103,11 @@ class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTModfrom posthog.hogql.database.database import Database# Internal managed-view construction (no user); bypass warehouse HogQL access control.- database = Database.create_for(self.team.pk, bypass_warehouse_access_control=True)+ database = Database.create_for(+ self.team.pk,+ bypass_warehouse_access_control=True,+ allowed_system_tables=DATA_MODELING_ALLOWED_SYSTEM_TABLES,+ )external_tables_by_view: dict[str, list] = {}for view in expected_views:temp_sq = DataWarehouseSavedQuery(@@ -197,7 +202,11 @@ class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTMod# creation entirely — no managed DAG is created for that kind.if saved_queries_to_schedule:managed_dag = DAG.get_or_create_revenue_analytics(self.team)- dag_database = Database.create_for(team=self.team, bypass_warehouse_access_control=True)+ dag_database = Database.create_for(+ team=self.team,+ bypass_warehouse_access_control=True,+ allowed_system_tables=DATA_MODELING_ALLOWED_SYSTEM_TABLES,+ )for saved_query in saved_queries_to_schedule:try:# reconcile once after both loops, not once per viewdiff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex b5396bcb1c46..ff23465f306f 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -16,7 +16,7 @@ if TYPE_CHECKING:from posthog.models.user import Userfrom posthog.hogql import ast-from posthog.hogql.database.database import Database+from posthog.hogql.database.database import Database, is_reserved_system_namefrom posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTablefrom posthog.hogql.database.direct_motherduck_table import DirectMotherDuckTablefrom posthog.hogql.database.direct_mysql_table import DirectMySQLTable@@ -47,7 +47,13 @@ logger = structlog.get_logger(__name__)TEST_VIEW_EXPIRY_INTERVAL = timedelta(days=7)-def validate_saved_query_name(value):+def validate_saved_query_name(value: str) -> None:+ if is_reserved_system_name(value):+ raise ValidationError(+ "The system namespace is reserved for built-in tables. Choose a different view name.",+ params={"value": value},+ )+if not re.match(r"^[A-Za-z_$][A-Za-z0-9_.$]*$", value):raise ValidationError(f"{value} is not a valid view name. View names can only contain letters, numbers, '_', '.', or '$' ",diff --git a/products/data_modeling/backend/models/modeling.py b/products/data_modeling/backend/models/modeling.pyindex a8f70931d287..97d8bf6165a4 100644--- a/products/data_modeling/backend/models/modeling.py+++ b/products/data_modeling/backend/models/modeling.py@@ -24,6 +24,7 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDTModel+from products.data_modeling.backend.facade.system_tables import DATA_MODELING_ALLOWED_SYSTEM_TABLESfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable@@ -493,6 +494,7 @@ def get_parents_from_model_query(modifiers=context.modifiers,team=context.team,bypass_warehouse_access_control=True,+ allowed_system_tables=DATA_MODELING_ALLOWED_SYSTEM_TABLES,)resolver = BoundedResolver(context=context, dialect="hogql", initial_view_name=model_name)@@ -790,7 +792,11 @@ class DataWarehouseModelPathManager(models.Manager["DataWarehouseModelPath"]):def get_hogql_database(self, team: Team) -> Database:"""Get the HogQL database for given team."""# Internal model-path resolution (no user); bypass warehouse HogQL access control.- return Database.create_for(team=team, bypass_warehouse_access_control=True)+ return Database.create_for(+ team=team,+ bypass_warehouse_access_control=True,+ allowed_system_tables=DATA_MODELING_ALLOWED_SYSTEM_TABLES,+ )def get_or_create_root_path_for_data_warehouse_table(self, data_warehouse_table: DataWarehouseTablediff --git a/products/data_modeling/backend/test/test_saved_query_dag_sync.py b/products/data_modeling/backend/test/test_saved_query_dag_sync.pyindex 6ea093743461..0c64e1dc70d7 100644--- a/products/data_modeling/backend/test/test_saved_query_dag_sync.py+++ b/products/data_modeling/backend/test/test_saved_query_dag_sync.py@@ -5,8 +5,9 @@ from unittest import mockfrom parameterized import parameterizedfrom posthog.hogql.database.database import Database-from posthog.hogql.errors import QueryError+from posthog.hogql.errors import QueryError, TableAccessDeniedError+from products.data_modeling.backend.facade.system_tables import DATA_MODELING_ALLOWED_SYSTEM_TABLESfrom products.data_modeling.backend.logic.saved_query_dag_sync import (HasDependentsError,ManagedDAGError,@@ -32,6 +33,32 @@ class TestGetDagId(BaseTest):@pytest.mark.django_dbclass TestSyncSavedQueryToDag(BaseTest):+ def test_saved_query_resolution_requires_explicit_data_modeling_system_allowlist(self) -> None:+ saved_query = DataWarehouseSavedQuery(+ name="account_summary",+ team=self.team,+ query={+ "kind": "HogQLQuery",+ "query": """+ SELECT+ id,+ feature_requests.count,+ email_threads.count+ FROM system.accounts+ """,+ },+ )++ with self.assertRaises(TableAccessDeniedError):+ _ = saved_query.s3_tables++ data_modeling_database = Database.create_for(+ team=self.team,+ bypass_warehouse_access_control=True,+ allowed_system_tables=DATA_MODELING_ALLOWED_SYSTEM_TABLES,+ )+ assert saved_query.get_s3_tables(database=data_modeling_database) == []+def test_sync_creates_dag_model(self):saved_query = DataWarehouseSavedQuery.objects.create(name="test_view",diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.pyindex 9707cbd81794..54702723d800 100644--- a/products/data_warehouse/backend/presentation/views/saved_query.py+++ b/products/data_warehouse/backend/presentation/views/saved_query.py@@ -872,7 +872,7 @@ class DataWarehouseSavedQuerySerializer(}view.set_columns(columns)- view.external_tables = view.s3_tables+ view.external_tables = view.get_s3_tables(database=self.context["database"])except Exception as e:capture_exception(e)logger.exception("Failed to retrieve types for view %s", view.name)@@ -1056,7 +1056,7 @@ class DataWarehouseSavedQuerySerializer(}view.set_columns(columns)- view.external_tables = view.s3_tables+ view.external_tables = view.get_s3_tables(database=self.context["database"])except RecursionError:raise serializers.ValidationError("Model contains a cycle")except Exception as e:diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.pyindex 993e9022c19f..2fc1d9b4d62f 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py@@ -7,6 +7,7 @@ from posthog.test.base import APIBaseTestfrom unittest import mockfrom unittest.mock import AsyncMock, patch+from django.core.exceptions import ValidationErrorfrom django.db import connectionfrom django.test import SimpleTestCasefrom django.test.utils import CaptureQueriesContext@@ -125,6 +126,46 @@ class TestSavedQuery(APIBaseTest):)self.assertIsNotNone(saved_query["latest_history_id"])+ def test_create_and_update_resolve_allowed_materialization_system_tables(self) -> None:+ create_response = self.client.post(+ f"/api/projects/{self.team.id}/warehouse_saved_queries/",+ {+ "name": "account_activity",+ "query": {+ "kind": "HogQLQuery",+ "query": """+ SELECT+ id,+ feature_requests.count AS feature_request_count,+ email_threads.count AS email_thread_count+ FROM system.accounts+ LIMIT 1+ """,+ },+ },+ )+ self.assertEqual(create_response.status_code, 201, create_response.content)++ update_response = self.client.patch(+ f"/api/projects/{self.team.id}/warehouse_saved_queries/{create_response.json()['id']}",+ {+ "query": {+ "kind": "HogQLQuery",+ "query": """+ SELECT+ id,+ name,+ feature_requests.count AS feature_request_count,+ email_threads.count AS email_thread_count+ FROM system.accounts+ LIMIT 1+ """,+ },+ "edited_history_id": create_response.json()["latest_history_id"],+ },+ )+ self.assertEqual(update_response.status_code, 200, update_response.content)+def test_upsert(self):response = self.client.post(f"/api/environments/{self.team.id}/warehouse_saved_queries/",@@ -360,6 +401,24 @@ class TestSavedQuery(APIBaseTest):saved_query = DataWarehouseSavedQuery.objects.get(id=view_id)assert saved_query.column_order == select_order+ def test_create_rejects_reserved_system_namespace(self) -> None:+ response = self.client.post(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/",+ {+ "name": "system.accounts",+ "query": {+ "kind": "HogQLQuery",+ "query": "select event as event from events LIMIT 100",+ },+ },+ )++ self.assertEqual(response.status_code, 400, response.content)+ self.assertEqual(+ response.json()["detail"],+ "The system namespace is reserved for built-in tables. Choose a different view name.",+ )+def test_create_name_overlap_error(self):response = self.client.post(f"/api/environments/{self.team.id}/warehouse_saved_queries/",@@ -2309,6 +2368,19 @@ class TestSavedQuery(APIBaseTest):cache.clear()+class TestSavedQueryNameValidation(SimpleTestCase):+ @parameterized.expand([("namespace", "system"), ("nested_name", "system.accounts")])+ def test_reserves_system_namespace(self, _name: str, saved_query_name: str) -> None:+ name_field = DataWarehouseSavedQuery._meta.get_field("name")++ with self.assertRaises(ValidationError) as error:+ name_field.run_validators(saved_query_name)++ assert error.exception.messages == [+ "The system namespace is reserved for built-in tables. Choose a different view name."+ ]++class TestMaterializeRequestBody(SimpleTestCase):@parameterized.expand([diff --git a/products/endpoints/backend/tests/test_endpoint_psak_auth.py b/products/endpoints/backend/tests/test_endpoint_psak_auth.pyindex d36c5b56b265..7a5475b710f2 100644--- a/products/endpoints/backend/tests/test_endpoint_psak_auth.py+++ b/products/endpoints/backend/tests/test_endpoint_psak_auth.py@@ -1,3 +1,5 @@+from collections.abc import Collection+from posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import patch@@ -11,7 +13,10 @@ from posthog.hogql.database.database import _compute_system_table_access_decisiofrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.project_secret_api_key import ProjectSecretAPIKeyfrom posthog.models.team import Team+from posthog.models.user import Userfrom posthog.models.utils import hash_key_value+from posthog.shared_link_user import SharedLinkUser+from posthog.synthetic_user import SyntheticUserfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.endpoints.backend.tests.conftest import create_endpoint_with_version@@ -180,10 +185,15 @@ class TestEndpointViewSetPSAKAuth(ClickhouseTestMixin, APIBaseTest):def test_psak_run_uses_synthetic_user_access_control(self):token, _ = _make_psak(self.team, label="run-with-rbac")- captured: dict = {}+ captured: dict[str, list[tuple[UserAccessControl | None, set[str]]]] = {}- def spy(team, user, user_access_control=None):- result = _compute_system_table_access_decision(team, user, user_access_control)+ def spy(+ team: Team,+ user: User | SyntheticUser | SharedLinkUser | None,+ user_access_control: UserAccessControl | None = None,+ allowed_system_tables: Collection[str] | None = None,+ ) -> tuple[UserAccessControl | None, set[str]]:+ result = _compute_system_table_access_decision(team, user, user_access_control, allowed_system_tables)captured.setdefault("results", []).append(result)return result