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.

feat(clickhouse): make the dagster cluster path token-aware (#104674)

Tommy Gilmore45bdd70c407f
diff --git a/posthog/clickhouse/client/AGENTS.md b/posthog/clickhouse/client/AGENTS.md
index 2a4be381fa2f..71d7171c26ec 100644
--- a/posthog/clickhouse/client/AGENTS.md
+++ b/posthog/clickhouse/client/AGENTS.md
@@ -15,6 +15,11 @@ It routes through `get_client_from_pool`, which uses the token-aware `get_pool`
The async temporal client `get_client` in `posthog/temporal/common/clickhouse.py` is token-aware too, because `_request_headers` calls `read_password` on each request.
Use these paths and token auth is automatic.
+`get_cluster` in `posthog/clickhouse/cluster.py` is token-aware for the pod default user: the per-host pools carry a credential provider that re-stamps the live token on each checkout.
+Its bootstrap discovery client is long-lived and cannot re-read the file, so it keeps the non-expiring static password when the user has one, and only a token-first user bakes the token into it.
+A caller that connects as a different user through `connection_overrides` owns its own credential.
+The backups and part_breaker Dagster resources do this: each sets `credential_provider` itself when its user is file-backed, the way `get_pool` does.
+
Token-awareness is lost when you pass your own `sync_client` to `sync_execute`, or build your own pool or client.
## A custom pool or client must stay token-aware
@@ -33,6 +38,8 @@ The canonical native implementation is `get_pool`.
An HTTP or one-shot client is rebuilt on each call, so it needs no credential provider.
Resolve the token once with `creds.read_password()` and pass it as the password, the way `get_http_kwargs` does.
+A client that is retained and reconnects is not one-shot: a token baked into it expires with no recovery, because `read_password`'s expired-token fallback only fires when it is called again.
+Give such a client the static password, or a refreshing pool.
## Wire the username, or the user falls back to the default user
diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.py
index 4a640e37b7b2..d61d04d5270c 100644
--- a/posthog/clickhouse/cluster.py
+++ b/posthog/clickhouse/cluster.py
@@ -18,7 +18,15 @@ from clickhouse_driver.errors import ServerException
from clickhouse_pool import ChPool
from posthog import settings
-from posthog.clickhouse.client.connection import NodeRole, Workload, _make_ch_pool, default_client
+from posthog.clickhouse.client.connection import (
+ ClickHouseUser,
+ NodeRole,
+ Workload,
+ _make_ch_pool,
+ default_client,
+ get_clickhouse_creds,
+ is_file_backed_user,
+)
from posthog.settings import CLICKHOUSE_PER_TEAM_SETTINGS
from posthog.settings.data_stores import CLICKHOUSE_CLUSTER, TEST
@@ -616,8 +624,20 @@ def get_cluster(
for host_config in map(copy, CLICKHOUSE_PER_TEAM_SETTINGS.values()):
extra_hosts.append(ConnectionInfo(host_config.pop("host"), None))
assert len(host_config) == 0, f"unexpected values: {host_config!r}"
+
+ # The bootstrap is a bare, long-lived client that cannot re-read the token file, so a baked token
+ # would expire mid-run with no recovery; it uses the non-expiring static password when one exists.
+ creds = get_clickhouse_creds(ClickHouseUser.DEFAULT)
+ overrides = dict(connection_overrides or {})
+ if is_file_backed_user(creds, Workload.DEFAULT, creds.user):
+ bootstrap_client = default_client(host=host, password=creds.password or creds.read_password())
+ if not overrides.keys() & {"user", "password", "credential_provider"}:
+ overrides["credential_provider"] = creds.read_password
+ else:
+ bootstrap_client = default_client(host=host)
+
return ClickhouseCluster(
- default_client(host=host),
+ bootstrap_client,
extra_hosts=extra_hosts,
logger=logger,
client_settings=client_settings,
@@ -625,7 +645,7 @@ def get_cluster(
data_cluster=data_cluster,
satellite_clusters=satellite_clusters,
retry_policy=retry_policy,
- connection_overrides=connection_overrides,
+ connection_overrides=overrides,
)
diff --git a/posthog/clickhouse/test/test_cluster.py b/posthog/clickhouse/test/test_cluster.py
index 22165509471c..26e230bb5159 100644
--- a/posthog/clickhouse/test/test_cluster.py
+++ b/posthog/clickhouse/test/test_cluster.py
@@ -12,7 +12,8 @@ from unittest.mock import Mock, patch, sentinel
from clickhouse_driver import Client
from clickhouse_driver.errors import ServerException
-from posthog.clickhouse.client.connection import NodeRole, Workload
+from posthog.clickhouse.client import connection
+from posthog.clickhouse.client.connection import ClickHouseCredentials, ClickHouseUser, NodeRole, Workload
from posthog.clickhouse.cluster import (
TOO_MANY_MUTATIONS,
AlterTableMutationRunner,
@@ -38,6 +39,61 @@ def cluster(django_db_setup) -> Iterator[ClickhouseCluster]:
yield get_cluster()
+ "static_password, password_file_set, overrides_arg, expected_bootstrap, expect_provider",
+ [
+ pytest.param("static-fallback", True, None, "static", True, id="dual_armed_default_bootstraps_on_static"),
+ pytest.param("", True, None, "token", True, id="token_first_default_bootstraps_on_token"),
+ pytest.param("static-only", False, None, "unset", False, id="static_default_uses_password"),
+ pytest.param(
+ "static-fallback",
+ True,
+ {"user": "backups", "password": "bkp-static"},
+ "static",
+ False,
+ id="override_user_keeps_its_own_credential",
+ ),
+ ],
+)
+def test_get_cluster_keeps_the_bootstrap_off_an_expirable_token(
+ monkeypatch, tmp_path, static_password, password_file_set, overrides_arg, expected_bootstrap, expect_provider
+) -> None:
+ token = "live-token"
+ token_file = tmp_path / "token"
+ token_file.write_text(token)
+ creds = ClickHouseCredentials(
+ user="default",
+ password=static_password,
+ password_file=str(token_file) if password_file_set else None,
+ )
+ monkeypatch.setattr(connection, "__user_dict", {ClickHouseUser.DEFAULT: creds})
+
+ with (
+ patch("posthog.clickhouse.cluster.default_client") as mock_default_client,
+ patch("posthog.clickhouse.cluster.ClickhouseCluster") as mock_cluster,
+ ):
+ get_cluster(connection_overrides=overrides_arg)
+
+ bootstrap_password = mock_default_client.call_args.kwargs.get("password")
+ overrides = mock_cluster.call_args.kwargs["connection_overrides"]
+
+ if expected_bootstrap == "static":
+ assert bootstrap_password == static_password
+ elif expected_bootstrap == "token":
+ assert bootstrap_password == token
+ else:
+ assert bootstrap_password is None
+
+ if expect_provider:
+ assert overrides["credential_provider"]() == token
+ else:
+ assert "credential_provider" not in overrides
+
+ if overrides_arg is not None:
+ assert overrides["user"] == overrides_arg["user"]
+ assert overrides["password"] == overrides_arg["password"]
+
+
def test_mutation_runner_rejects_invalid_parameters() -> None:
with pytest.raises(ValueError):
AlterTableMutationRunner(table="table", commands={"command"}, parameters={"__invalid_key": True})
diff --git a/posthog/dags/common/resources.py b/posthog/dags/common/resources.py
index b84eb7ce6d32..2a02c152fefc 100644
--- a/posthog/dags/common/resources.py
+++ b/posthog/dags/common/resources.py
@@ -15,7 +15,13 @@ import posthoganalytics
from clickhouse_driver.errors import Error, ErrorCodes
from posthog import settings
-from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_creds
+from posthog.clickhouse.client.connection import (
+ ClickHouseCredentials,
+ ClickHouseUser,
+ Workload,
+ get_clickhouse_creds,
+ is_file_backed_user,
+)
from posthog.clickhouse.cluster import ClickhouseCluster, ExponentialBackoff, RetryPolicy, get_cluster
from posthog.kafka_client.client import _KafkaProducer
from posthog.kafka_client.profiles import KafkaClusterProfile
@@ -58,6 +64,22 @@ def _is_retryable_clickhouse_exception(e: Exception) -> bool:
)
+def _dedicated_user_connection_overrides(creds: ClickHouseCredentials) -> dict[str, Any]:
+ """Build get_cluster connection_overrides for a dedicated ClickHouse user.
+
+ Mirrors the file-backed branch of get_pool: a user whose credential comes from a rotating token
+ file passes a credential_provider so RefreshingChPool re-stamps the live token on each checkout,
+ while a static-password user passes the password directly. get_cluster leaves the user override
+ untouched, so the pool authenticates as this user with this user's credential.
+ """
+ overrides: dict[str, Any] = {"user": creds.user}
+ if is_file_backed_user(creds, Workload.DEFAULT, creds.user):
+ overrides["credential_provider"] = creds.read_password
+ else:
+ overrides["password"] = creds.password
+ return overrides
+
+
class ClickhouseClusterResource(dagster.ConfigurableResource):
"""
The ClickHouse cluster used to run the job.
@@ -124,7 +146,8 @@ class BackupsClickhouseClusterResource(dagster.ConfigurableResource):
"""
ClickHouse cluster resource that connects as the dedicated 'backups' user.
- Requires CLICKHOUSE_BACKUPS_USER and CLICKHOUSE_BACKUPS_PASSWORD env vars.
+ Requires CLICKHOUSE_BACKUPS_USER and either CLICKHOUSE_BACKUPS_PASSWORD or
+ CLICKHOUSE_BACKUPS_PASSWORD_FILE env vars.
The backups user must have a server-side settings profile with
use_concurrency_control=0 (configured in users.xml via Ansible) because
async BACKUP threads don't inherit session-level settings.
@@ -160,7 +183,7 @@ class BackupsClickhouseClusterResource(dagster.ConfigurableResource):
delay=ExponentialBackoff(20, max_delay=60),
exceptions=_is_retryable_clickhouse_exception,
),
- connection_overrides={"user": creds.user, "password": creds.password},
+ connection_overrides=_dedicated_user_connection_overrides(creds),
)
@@ -168,7 +191,8 @@ class PartBreakerClickhouseClusterResource(dagster.ConfigurableResource):
"""
ClickHouse cluster resource that connects as the dedicated 'part_breaker' user.
- Requires CLICKHOUSE_PART_BREAKER_USER and CLICKHOUSE_PART_BREAKER_PASSWORD env vars.
+ Requires CLICKHOUSE_PART_BREAKER_USER and either CLICKHOUSE_PART_BREAKER_PASSWORD or
+ CLICKHOUSE_PART_BREAKER_PASSWORD_FILE env vars.
The part_breaker user needs SELECT on system tables, CREATE/DROP/INSERT/ALTER on
staging tables, and ALTER FREEZE / DROP PART on source tables.
"""
@@ -197,7 +221,7 @@ class PartBreakerClickhouseClusterResource(dagster.ConfigurableResource):
delay=ExponentialBackoff(20, max_delay=60),
exceptions=_is_retryable_clickhouse_exception,
),
- connection_overrides={"user": creds.user, "password": creds.password},
+ connection_overrides=_dedicated_user_connection_overrides(creds),
)
diff --git a/posthog/dags/tests/test_resources.py b/posthog/dags/tests/test_resources.py
new file mode 100644
index 000000000000..b72582dd8246
--- /dev/null
+++ b/posthog/dags/tests/test_resources.py
@@ -0,0 +1,25 @@
+import pytest
+
+from posthog.clickhouse.client.connection import ClickHouseCredentials
+from posthog.dags.common.resources import _dedicated_user_connection_overrides
+
+
[email protected]("file_backed", [True, False], ids=["file_backed_uses_the_token", "static_keeps_its_password"])
+def test_dedicated_user_connection_overrides(tmp_path, file_backed) -> None:
+ token_file = tmp_path / "token"
+ token_file.write_text("live-token")
+ creds = ClickHouseCredentials(
+ user="backups",
+ password="static-password",
+ password_file=str(token_file) if file_backed else None,
+ )
+
+ overrides = _dedicated_user_connection_overrides(creds)
+
+ assert overrides["user"] == "backups"
+ if file_backed:
+ assert "password" not in overrides
+ assert overrides["credential_provider"]() == "live-token"
+ else:
+ assert "credential_provider" not in overrides
+ assert overrides["password"] == "static-password"