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(hogql): partition the query cache on hidden system tables' scope (#97564)

Marius Andra402d4e669b16
diff --git a/docs/internal/hogql-system-table-cache.md b/docs/internal/hogql-system-table-cache.md
new file mode 100644
index 000000000000..cecc7c01ade4
--- /dev/null
+++ b/docs/internal/hogql-system-table-cache.md
@@ -0,0 +1,18 @@
+# HogQL system table cache permissions
+
+Query cache keys must account for every permission scope that can change the result.
+A cache hit returns before schema resolution and table predicates run.
+`queried_access_controlled_resources` collects these scopes before the query runner builds its cache key.
+
+Tables with an `access_scope` contribute that scope directly.
+Hidden tables whose predicates read scoped parents contribute those parents through `_TRANSITIVE_SYSTEM_TABLE_SCOPES`.
+This includes the account tag and notebook junctions, ticket tag and assignment junctions, and ticket assignee roles.
+The cache fingerprint includes resource denials, object denials, object grants, and the caller identity needed for creator exemptions.
+
+Keep row filtering on the parent when a junction already uses a predicate such as `account_id IN (SELECT id FROM system.accounts)`.
+That predicate applies the parent's team and object permissions, including its creator exemption.
+Adding a separate object-ID filter to the junction can hide child rows that the parent permits its creator to read.
+
+When adding a hidden system table, declare its direct or transitive cache scope and test the resulting cache key under different permissions.
+Also verify that its predicates deny unauthorized reads and preserve object grants and creator exemptions.
+Userless data-modeling queries must resolve the parent through `DATA_MODELING_ALLOWED_SYSTEM_TABLES`; a transitive cache entry does not grant access.
diff --git a/posthog/hogql/ACCESS_CONTROL.md b/posthog/hogql/ACCESS_CONTROL.md
index 9c56a7119b6e..cd9cc5d89069 100644
--- a/posthog/hogql/ACCESS_CONTROL.md
+++ b/posthog/hogql/ACCESS_CONTROL.md
@@ -243,6 +243,9 @@ Two things keep cache hit rates high:
When a run has no user but does read access-controlled resources, the fingerprint uses `restricted_resources: ["*"]` so it can never collide with a real user's cache, and synthetic principals partition on their readable scopes so a narrow token can't reuse a broader token's cached rows.
+Hidden backing tables also contribute their parent scopes through `_TRANSITIVE_SYSTEM_TABLE_SCOPES`, even when they have no `access_scope` of their own.
+Their parent predicates enforce row permissions, including creator exemptions; see [HogQL system table cache permissions](../../docs/internal/hogql-system-table-cache.md) before adding a separate junction-table guard.
+
## One preloaded `UserAccessControl` everywhere
`UserAccessControl` (`products/access_control/backend/facade/user_access_control.py`) bulk-fetches every access control row relevant to the user on the team in a single query (`_cached_access_controls`, covering team defaults, the user's membership, and the user's roles), then resolves all checks in memory (`access_level_for_resource`, `check_access_level_for_object`, `blocked_resource_ids_by_scope`, ...).
diff --git a/posthog/hogql/printer/test/test_hogql_access_control.py b/posthog/hogql/printer/test/test_hogql_access_control.py
index 95ba0d46bb5b..11a4a358eca8 100644
--- a/posthog/hogql/printer/test/test_hogql_access_control.py
+++ b/posthog/hogql/printer/test/test_hogql_access_control.py
@@ -447,25 +447,34 @@ class TestRestParityForObjectGrants(BaseTest):
@parameterized.expand(
[
- ("resource_denied", "none", "in(toString(system__dashboards.id)"),
- ("resource_granted", "editor", "notIn(toString(system__dashboards.id)"),
+ (f"{name}_{table}", resource_level, scope, parent, table, operator)
+ for name, resource_level, operator in (
+ ("resource_denied", "none", "in"),
+ ("resource_granted", "editor", "notIn"),
+ )
+ for scope, parent, table in (
+ ("dashboard", "dashboards", "dashboards"),
+ ("account", "accounts", "_account_tagged_items"),
+ ("account", "accounts", "_account_resource_notebooks"),
+ )
]
)
- def test_creator_keeps_their_own_denied_object(self, _name, resource_level, expected_id_guard):
- # REST exempts the creator from object-level denial on both branches of the filter, so a
- # dashboard's creator must not lose it to HogQL either.
- self._ac(resource="dashboard", access_level=resource_level)
+ def test_creator_keeps_their_own_denied_object(
+ self, _name: str, resource_level: str, scope: str, parent: str, table: str, operator: str
+ ) -> None:
+ self._ac(resource="customer_analytics" if scope == "account" else scope, access_level=resource_level)
self._ac(
- resource="dashboard",
- resource_id="dash-mine",
+ resource=scope,
+ resource_id="018f0000-0000-0000-0000-000000000001",
access_level="none" if resource_level == "editor" else "viewer",
organization_member=self.membership,
)
- sql, _context = self._compile("SELECT id FROM system.dashboards")
- assert expected_id_guard in sql
- assert f"ifNull(equals(system__dashboards.created_by_id, {self.user.pk}), 0)" in sql
+ sql, context = self._compile(f"SELECT id FROM system.{table}")
+ assert f"{operator}(toString(system__{parent}.id)" in sql
+ assert f"ifNull(equals(system__{parent}.created_by_id, {self.user.pk}), 0)" in sql
assert sql.count("or(") == 1
+ assert len(self._id_list_placeholders(context)) == 1
class TestDeniedTableError(BaseTest):
@@ -550,8 +559,17 @@ class TestAccessControlIntegration(BaseTest):
assert "id" in sql
assert "name" in sql
- def test_query_without_user_fails_on_scoped_table(self):
- """Querying a scoped system table without user should fail with access error."""
+ @parameterized.expand(
+ [
+ ("dashboards",),
+ ("_account_tagged_items",),
+ ("_account_resource_notebooks",),
+ ("_ticket_tagged_items",),
+ ("_ticket_assignments",),
+ ("_ticket_assignee_roles",),
+ ]
+ )
+ def test_query_without_user_fails_on_scoped_table(self, table: str) -> None:
context = HogQLContext(
team_id=self.team.pk,
team=self.team,
@@ -560,7 +578,7 @@ class TestAccessControlIntegration(BaseTest):
)
with self.assertRaises(TableAccessDeniedError):
- self._compile_select("SELECT id, name FROM system.dashboards", context)
+ self._compile_select(f"SELECT id FROM system.{table}", context)
def test_query_without_user_works_for_unscoped_tables(self):
"""Unscoped system tables should still be queryable without user context."""
diff --git a/posthog/hogql_queries/access_controlled_resources.py b/posthog/hogql_queries/access_controlled_resources.py
index 318f2d643a70..fa7a482f4cc8 100644
--- a/posthog/hogql_queries/access_controlled_resources.py
+++ b/posthog/hogql_queries/access_controlled_resources.py
@@ -47,12 +47,22 @@ _DATA_QUALITY_INFORMATION_SCHEMA_TABLES = frozenset(
_ACCOUNT_COMMUNICATION_LAZY_FIELDS = frozenset({"email_threads", "support_tickets"})
# Scopes a system table's rows depend on beyond its own `access_scope`, because its visibility rules
-# read another access-controlled table. `system.activity_logs` limits Canvas rows to the canvases in
-# `system.canvases` (see activity_log_visibility.py), so its rows follow the caller's Canvas grants:
-# without partitioning on `canvas` too, two users with identical activity-log access but different
-# Canvas grants share one cache key, and the narrower one is served the wider one's Canvas rows.
+# read another access-controlled table, or because it declares no scope of its own.
+# `system.activity_logs` limits Canvas rows to the canvases in `system.canvases` (see
+# activity_log_visibility.py), so its rows follow the caller's Canvas grants: without partitioning
+# on `canvas` too, two users with identical activity-log access but different Canvas grants share
+# one cache key, and the narrower one is served the wider one's Canvas rows.
_TRANSITIVE_SYSTEM_TABLE_SCOPES: dict[str, frozenset[str]] = {
"system.activity_logs": frozenset({"canvas"}),
+ # These predicates resolve scoped parents at execution, after a cache hit would return.
+ # Keep row filtering on the parent so its creator exemption also applies to junction rows.
+ "system._account_tagged_items": frozenset({"account"}),
+ "system._account_resource_notebooks": frozenset({"account"}),
+ "system._ticket_tagged_items": frozenset({"ticket"}),
+ "system._ticket_assignments": frozenset({"ticket"}),
+ "system._ticket_assignee_roles": frozenset({"ticket"}),
+ # Task predicates need these public channel IDs even under object-only task grants.
+ "system._task_public_channels": frozenset({"task"}),
"system.customer_tasks": frozenset({"account"}),
}
diff --git a/posthog/hogql_queries/test/test_access_controlled_resources.py b/posthog/hogql_queries/test/test_access_controlled_resources.py
index 076df7d89932..34961864fd73 100644
--- a/posthog/hogql_queries/test/test_access_controlled_resources.py
+++ b/posthog/hogql_queries/test/test_access_controlled_resources.py
@@ -1,5 +1,7 @@
from posthog.test.base import BaseTest
+from django.test import SimpleTestCase
+
from parameterized import parameterized
from posthog.schema import (
@@ -19,8 +21,11 @@ from posthog.schema import (
)
from posthog.hogql.database.database import get_data_warehouse_table_name
+from posthog.hogql.database.postgres_table import PostgresTable
+from posthog.hogql.database.schema.system import SystemTables
from posthog.hogql_queries.access_controlled_resources import (
+ _TRANSITIVE_SYSTEM_TABLE_SCOPES,
_references_data_warehouse,
queried_access_controlled_resources,
)
@@ -80,6 +85,12 @@ class TestQueriedAccessControlledResources(BaseTest):
# Activity-log rows for canvases are limited to the canvases in `system.canvases`, so the
# rows follow the caller's canvas grants as well as their activity-log access.
("activity_logs", "select * from system.activity_logs", {"activity_log", "canvas"}),
+ ("account_tagged_items", "select * from system._account_tagged_items", {"account"}),
+ ("account_resource_notebooks", "select * from system._account_resource_notebooks", {"account"}),
+ ("ticket_tagged_items", "select * from system._ticket_tagged_items", {"ticket"}),
+ ("ticket_assignments", "select * from system._ticket_assignments", {"ticket"}),
+ ("ticket_assignee_roles", "select * from system._ticket_assignee_roles", {"ticket"}),
+ ("task_public_channels", "select * from system._task_public_channels", {"task"}),
("customer_tasks", "select * from system.customer_tasks", {"customer_task", "account"}),
("no_access_controlled_table", "select 1", set()),
("events_table", "select * from events", set()),
@@ -298,3 +309,20 @@ class TestQueriedAccessControlledResources(BaseTest):
# A name that resolves to a warehouse table in a different team must not grant the scope here.
result = queried_access_controlled_resources(HogQLQuery(query="select * from other_team_table"), self.team)
assert result == set()
+
+
+class TestHiddenSystemTableCachePartitioning(SimpleTestCase):
+ def test_every_hidden_system_table_partitions_the_cache(self) -> None:
+ unpartitioned = sorted(
+ name
+ for name, node in SystemTables().children.items()
+ if node.hidden
+ and isinstance(node.table, PostgresTable)
+ and node.table.access_scope is None
+ and not _TRANSITIVE_SYSTEM_TABLE_SCOPES.get(f"system.{name}")
+ )
+ assert not unpartitioned, (
+ f"Hidden system tables with no cache partitioning: {unpartitioned}. Declare the "
+ f"`access_scope` the table's rows sit under, or add the scopes its predicates depend "
+ f"on to _TRANSITIVE_SYSTEM_TABLE_SCOPES."
+ )
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 4830a466dbc5..82c254f41dcb 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -1723,16 +1723,28 @@ class TestQueryRunnerAccessControlFingerprint(BaseTest):
assert no_user_payload["restricted_resources"] == ["*"]
assert self._runner(None, base).get_cache_key() != self._runner(self.user, base).get_cache_key()
- def test_hogql_query_runner_partitions_cache_on_access_control(self):
+ @parameterized.expand(
+ [
+ ("notebooks", "notebook"),
+ ("_account_tagged_items", "account"),
+ ("_account_resource_notebooks", "account"),
+ ("_ticket_tagged_items", "ticket"),
+ ("_ticket_assignments", "ticket"),
+ ("_ticket_assignee_roles", "ticket"),
+ ("_task_public_channels", "task"),
+ ]
+ )
+ def test_hogql_query_runner_partitions_cache_on_access_control(self, table: str, scope: str) -> None:
# Raw HogQL is the only way to reach access-controlled system.* tables.
- query = {"kind": "HogQLQuery", "query": "select * from system.notebooks"}
+ query = {"kind": "HogQLQuery", "query": f"select * from system.{table}"}
- self._ac(resource="notebook", access_level="none")
+ resource = "customer_analytics" if scope == "account" else scope
+ self._ac(resource=resource, access_level="none")
denied_runner = HogQLQueryRunner(query=query, team=self.team, user=self.user)
- assert "notebook" in (denied_runner.get_cache_payload().get("restricted_resources") or [])
+ assert scope in (denied_runner.get_cache_payload().get("restricted_resources") or [])
key_denied = denied_runner.get_cache_key()
- self._ac(resource="notebook", access_level="editor")
+ self._ac(resource=resource, access_level="editor")
key_granted = HogQLQueryRunner(query=query, team=self.team, user=self.user).get_cache_key()
assert key_denied != key_granted
diff --git a/products/data_modeling/backend/test/test_saved_query_dag_sync.py b/products/data_modeling/backend/test/test_saved_query_dag_sync.py
index 987a5c118a3a..9b1d5d882359 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
@@ -42,8 +42,9 @@ class TestSyncSavedQueryToDag(BaseTest):
[
(
"account_summary",
- "SELECT id, feature_requests.count, email_threads.count FROM system.accounts",
+ "SELECT id, feature_requests.count, email_threads.count, tags.names, notebooks.count FROM system.accounts",
),
+ ("ticket_summary", "SELECT id, tags.names, assignee.role_name FROM system.support_tickets"),
("customer_tasks", "SELECT id, name, account_id FROM system.customer_tasks"),
]
)