: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
feat(clickhouse): move dagster dictionaries onto dagster_dict_reader (#112108)
Tommy Gilmorea3ecd1f2db52
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.pyindex 3684252558b7..51bd4a4d5517 100644--- a/posthog/clickhouse/client/connection.py+++ b/posthog/clickhouse/client/connection.py@@ -121,6 +121,9 @@ class ClickHouseUser(StrEnum):# Low-privilege reader baked into dictionary SOURCE blocks, decoupling# dictionary credentials from the default user.DICT_READER = "dict_reader"+ # Static reader that Dagster embeds in dictionary SOURCE blocks. ClickHouse stores the+ # SOURCE password, so this user cannot use the rotating token.+ DAGSTER_DICT_READER = "dagster_dict_reader"EXPIRED_TOKEN_PASSWORD_FALLBACK_COUNTER = Counter(diff --git a/posthog/dags/clickhouse_cleanup.py b/posthog/dags/clickhouse_cleanup.pyindex 2fafc4b1bd2c..b5df5151902d 100644--- a/posthog/dags/clickhouse_cleanup.py+++ b/posthog/dags/clickhouse_cleanup.py@@ -35,7 +35,6 @@ from posthog.clickhouse.cleanup_snapshots import (CLEANUP_REVIVED_PERSONS_TABLE,CLEANUP_SNAPSHOT_TABLES,)-from posthog.clickhouse.client.connection import ClickHouseCredentials, ClickHouseUser, get_clickhouse_credsfrom posthog.clickhouse.cluster import ClickhouseCluster, LightweightDeleteMutationRunner, MutationWaiter, NodeRolefrom posthog.clickhouse.custom_metrics import MetricsClientfrom posthog.clickhouse.workload import Workload@@ -426,12 +425,6 @@ class SnapshotDictionary(Dictionary):GROUP BY {self.key_columns}"""- @property- def credentials(self) -> ClickHouseCredentials:- # The source reads as the low-privilege dict_reader user, which falls back to the default- # user's credentials where dict_reader is not provisioned.- return get_clickhouse_creds(ClickHouseUser.DICT_READER)-def staged(self) -> StagedDictionary:# A staged copy is a static object. The revival checkpoints exclude keys by reloading this# dictionary so its source query re-runs against the live exclusion table, and a reloaddiff --git a/posthog/dags/common/dictionaries.py b/posthog/dags/common/dictionaries.pyindex 6d6fed4af073..3cd1f27985d2 100644--- a/posthog/dags/common/dictionaries.py+++ b/posthog/dags/common/dictionaries.py@@ -64,10 +64,11 @@ class Dictionary(abc.ABC):def credentials(self) -> ClickHouseCredentials:"""Credentials the dictionary source reads as.- Defaults to the default user. Override only when the role's SELECT grants on the source- tables are known to exist in every environment; grants live in infra, not this repo.+ The dictionary stores this password, so create passes the static password and never a+ token, which would expire. dagster_dict_reader can only SELECT the source tables that infra+ grants it, so a new source table needs a grant there first or the dictionary fails to load."""- return get_clickhouse_creds(ClickHouseUser.DEFAULT)+ return get_clickhouse_creds(ClickHouseUser.DAGSTER_DICT_READER)@propertydef qualified_name(self) -> str:diff --git a/posthog/dags/person_overrides.py b/posthog/dags/person_overrides.pyindex 42e5e276e5b6..48a3965a7465 100644--- a/posthog/dags/person_overrides.py+++ b/posthog/dags/person_overrides.py@@ -8,6 +8,7 @@ import pydanticfrom clickhouse_driver import Clientfrom posthog import settings+from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_credsfrom posthog.clickhouse.cluster import ClickhouseCluster, MutationWaiter, wait_for_mutations_on_shardsfrom posthog.dags.common import JobOwnersfrom posthog.dags.common.overrides_manager import OverridesSnapshotDictionary, OverridesSnapshotTable@@ -97,6 +98,7 @@ class PersonOverridesSnapshotDictionary(OverridesSnapshotDictionary):# A host that cannot see the snapshot table reads the staged object instead, which is a# query rather than a table name.source = "QUERY %(query)s" if query else "TABLE %(table)s"+ creds = get_clickhouse_creds(ClickHouseUser.DAGSTER_DICT_READER)client.execute(f"""CREATE DICTIONARY IF NOT EXISTS {self.qualified_name} (@@ -115,8 +117,8 @@ class PersonOverridesSnapshotDictionary(OverridesSnapshotDictionary):"database": settings.CLICKHOUSE_DATABASE,"table": self.source.name,"query": query,- "user": settings.CLICKHOUSE_USER,- "password": settings.CLICKHOUSE_PASSWORD,+ "user": creds.user,+ "password": creds.password,},)diff --git a/posthog/dags/tests/test_common_dictionaries.py b/posthog/dags/tests/test_common_dictionaries.pyindex b9964105b940..4bfac7a5d4cb 100644--- a/posthog/dags/tests/test_common_dictionaries.py+++ b/posthog/dags/tests/test_common_dictionaries.py@@ -1,3 +1,4 @@+import uuidimport itertoolsfrom collections.abc import Iterablefrom datetime import datetime@@ -7,6 +8,7 @@ import pytestfrom clickhouse_driver.client import Client+from posthog.clickhouse.client import connectionfrom posthog.clickhouse.client.connection import ClickHouseCredentials, ClickHouseUserfrom posthog.dags import clickhouse_cleanupfrom posthog.dags.common import dictionaries@@ -18,6 +20,7 @@ from posthog.dags.deletes import (PendingDeletesDictionary,PendingDeletesTable,)+from posthog.dags.person_overrides import PersonOverridesSnapshotDictionary, PersonOverridesSnapshotTablefrom posthog.dataclasses import frozen@@ -130,33 +133,36 @@ def _snapshot_dictionary() -> clickhouse_cleanup.SnapshotDictionary:)+def _person_overrides_snapshot_dictionary() -> PersonOverridesSnapshotDictionary:+ return PersonOverridesSnapshotDictionary(source=PersonOverridesSnapshotTable(id=uuid.UUID(int=1)))++@pytest.mark.parametrize(- "make_dictionary,expected_user",+ "make_dictionary",[- (_pending_deletes_dictionary, "app_default"),- (_adhoc_event_deletes_dictionary, "app_default"),- (_snapshot_dictionary, "reader"),+ _pending_deletes_dictionary,+ _adhoc_event_deletes_dictionary,+ _snapshot_dictionary,+ _person_overrides_snapshot_dictionary,],)-def test_create_reads_the_source_as_each_callers_credentials(- monkeypatch: pytest.MonkeyPatch, make_dictionary: Any, expected_user: str-) -> None:- # The GDPR job's dictionaries must keep reading as the default user until dict_reader's- # SELECT grants on its per-run tables are proven in every environment; the sweep already- # reads as dict_reader. A shared-lifecycle change that flips either breaks a weekly prod job.- creds = {- ClickHouseUser.DEFAULT: ClickHouseCredentials(user="app_default", password="p1"),- ClickHouseUser.DICT_READER: ClickHouseCredentials(user="reader", password="p2"),- }- monkeypatch.setattr(dictionaries, "get_clickhouse_creds", creds.__getitem__)- monkeypatch.setattr(clickhouse_cleanup, "get_clickhouse_creds", creds.__getitem__)+def test_create_reads_the_source_as_dagster_dict_reader(monkeypatch: pytest.MonkeyPatch, make_dictionary: Any) -> None:+ # A dictionary that embeds the default user's password keeps that password from being dropped.+ monkeypatch.setattr(+ connection,+ "__user_dict",+ {+ ClickHouseUser.DEFAULT: ClickHouseCredentials(user="app_default", password="p1"),+ ClickHouseUser.DAGSTER_DICT_READER: ClickHouseCredentials(user="reader", password="p2"),+ },+ )client = _ScriptedClient()make_dictionary().create(cast(Client, client), shards=1, max_execution_time=0, max_memory_usage=0)[(query, params)] = client.executedassert "CREATE DICTIONARY" in query- assert params is not None and params["user"] == expected_user+ assert params is not None and (params["user"], params["password"]) == ("reader", "p2")def test_create_can_read_a_staged_object_instead_of_the_source() -> None: