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): stamp the live token on the get_cluster bootstrap (#108611)

Tommy Gilmore7242658efa38
diff --git a/posthog/clickhouse/client/AGENTS.md b/posthog/clickhouse/client/AGENTS.md
index 71d7171c26ec..0315bef56cb9 100644
--- a/posthog/clickhouse/client/AGENTS.md
+++ b/posthog/clickhouse/client/AGENTS.md
@@ -16,7 +16,7 @@ The async temporal client `get_client` in `posthog/temporal/common/clickhouse.py
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.
+Its bootstrap discovery client is long-lived, so each discovery attempt stamps the live token onto it first, including the discovery that `sibling()` runs hours into a job.
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.
@@ -39,7 +39,7 @@ 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.
+Stamp `read_password()` onto `client.connection.password` before each use, the way the `get_cluster` bootstrap does, or use 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 b2cd26ebf2a3..de04671ae615 100644
--- a/posthog/clickhouse/cluster.py
+++ b/posthog/clickhouse/cluster.py
@@ -9,7 +9,7 @@ from collections import defaultdict
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence, Set
from concurrent.futures import ALL_COMPLETED, FIRST_EXCEPTION, Future, ThreadPoolExecutor, as_completed
from copy import copy
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from datetime import datetime
from typing import Any, ClassVar, Generic, Literal, NamedTuple, TypeVar
@@ -27,6 +27,7 @@ from posthog.clickhouse.client.connection import (
get_clickhouse_creds,
is_file_backed_user,
)
+from posthog.dataclasses import frozen
from posthog.settings import CLICKHOUSE_PER_TEAM_SETTINGS
from posthog.settings.data_stores import CLICKHOUSE_CLUSTER, TEST
@@ -174,6 +175,7 @@ class ClickhouseCluster:
retry_policy: RetryPolicy | None = None,
connection_overrides: Mapping[str, Any] | None = None,
shard_role: NodeRole = NodeRole.DATA,
+ bootstrap_credential_provider: Callable[[], str] | None = None,
) -> None:
if logger is None:
logger = logging.getLogger(__name__)
@@ -191,7 +193,16 @@ class ClickhouseCluster:
# nodes whose role is `events`, and reading their shard numbers as absent would leave this
# handle with no shards to dispatch over at all.
self.__shard_role = shard_role
- cluster_hosts = self.__get_cluster_hosts(bootstrap_client, migrations_cluster, retry_policy)
+ self.__bootstrap_credential_provider = bootstrap_credential_provider
+ # A token login fails while the ch-podauth bridge on the answering node is down, so discovery retries it.
+ discovery_retry_policy = retry_policy
+ if bootstrap_credential_provider is not None:
+ discovery_retry_policy = (
+ retry_policy.also_retrying(_is_authentication_failure)
+ if retry_policy is not None
+ else _REJECTED_LOGIN_RETRY_POLICY
+ )
+ cluster_hosts = self.__get_cluster_hosts(bootstrap_client, migrations_cluster, discovery_retry_policy)
for row in cluster_hosts:
(host_name, port, shard_num, replica_num, host_cluster_type, host_cluster_role) = row
@@ -212,7 +223,7 @@ class ClickhouseCluster:
# the main posthog cluster which has the complete shard topology
if data_cluster and data_cluster != migrations_cluster:
self.__shards.clear()
- data_hosts = self.__get_cluster_hosts(bootstrap_client, data_cluster, retry_policy)
+ data_hosts = self.__get_cluster_hosts(bootstrap_client, data_cluster, discovery_retry_policy)
for row in data_hosts:
(host_name, port, shard_num, replica_num, host_cluster_type, host_cluster_role) = row
if host_cluster_role == shard_role:
@@ -235,7 +246,7 @@ class ClickhouseCluster:
for satellite_name in satellite_clusters or []:
satellite_hosts = self.__get_satellite_cluster_hosts(
- bootstrap_client, satellite_name, migrations_cluster, retry_policy
+ bootstrap_client, satellite_name, migrations_cluster, discovery_retry_policy
)
logger.info("Discovered %d hosts from satellite cluster %r", len(satellite_hosts), satellite_name)
for row in satellite_hosts:
@@ -303,23 +314,30 @@ class ClickhouseCluster:
retry_policy=self.__retry_policy,
connection_overrides=self.__connection_overrides,
shard_role=shard_role,
+ bootstrap_credential_provider=self.__bootstrap_credential_provider,
)
return sibling
+ def __stamp_bootstrap_credential(self, client: Client) -> None:
+ # sibling() runs discovery on this client hours into a job, and a reconnect sends the stored password.
+ if self.__bootstrap_credential_provider is not None:
+ client.connection.password = self.__bootstrap_credential_provider()
+
def __get_cluster_hosts(self, client: Client, cluster: str, retry_policy: RetryPolicy | None = None):
- get_cluster_hosts_fn = lambda client: client.execute(
- f"""
- SELECT host_name, port, shard_num, replica_num, getMacro('hostClusterType') as host_cluster_type, getMacro('hostClusterRole') as host_cluster_role
- FROM clusterAllReplicas(%(name)s, system.clusters)
- WHERE name = %(name)s and is_local
- ORDER BY shard_num, replica_num
- """,
- {"name": cluster},
- )
+ def get_cluster_hosts_fn(client: Client) -> list[tuple[Any, ...]]:
+ self.__stamp_bootstrap_credential(client)
+ return client.execute(
+ f"""
+ SELECT host_name, port, shard_num, replica_num, getMacro('hostClusterType') as host_cluster_type, getMacro('hostClusterRole') as host_cluster_role
+ FROM clusterAllReplicas(%(name)s, system.clusters)
+ WHERE name = %(name)s and is_local
+ ORDER BY shard_num, replica_num
+ """,
+ {"name": cluster},
+ )
if retry_policy is not None:
- get_cluster_hosts_fn = retry_policy(get_cluster_hosts_fn)
-
+ return retry_policy(get_cluster_hosts_fn)(client)
return get_cluster_hosts_fn(client)
def __get_satellite_cluster_hosts(
@@ -329,19 +347,20 @@ class ClickhouseCluster:
migrations_cluster: str,
retry_policy: RetryPolicy | None = None,
):
- get_hosts_fn = lambda client: client.execute(
- """
- SELECT host_name, port, shard_num, replica_num, getMacro('hostClusterType') as host_cluster_type, getMacro('hostClusterRole') as host_cluster_role
- FROM clusterAllReplicas(%(satellite_name)s, system.clusters)
- WHERE is_local AND cluster = %(migrations_cluster)s
- ORDER BY shard_num, replica_num
- """,
- {"satellite_name": satellite_cluster, "migrations_cluster": migrations_cluster},
- )
+ def get_hosts_fn(client: Client) -> list[tuple[Any, ...]]:
+ self.__stamp_bootstrap_credential(client)
+ return client.execute(
+ """
+ SELECT host_name, port, shard_num, replica_num, getMacro('hostClusterType') as host_cluster_type, getMacro('hostClusterRole') as host_cluster_role
+ FROM clusterAllReplicas(%(satellite_name)s, system.clusters)
+ WHERE is_local AND cluster = %(migrations_cluster)s
+ ORDER BY shard_num, replica_num
+ """,
+ {"satellite_name": satellite_cluster, "migrations_cluster": migrations_cluster},
+ )
if retry_policy is not None:
- get_hosts_fn = retry_policy(get_hosts_fn)
-
+ return retry_policy(get_hosts_fn)(client)
return get_hosts_fn(client)
def __get_task_function(self, host: HostInfo, fn: Callable[[Client], T]) -> Callable[[], T]:
@@ -625,12 +644,12 @@ def get_cluster(
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 {})
+ bootstrap_credential_provider: Callable[[], str] | None = None
if is_file_backed_user(creds, Workload.DEFAULT, creds.user):
- bootstrap_client = default_client(host=host, password=creds.password or creds.read_password())
+ bootstrap_credential_provider = creds.read_password
+ bootstrap_client = default_client(host=host, password=creds.read_password())
if not overrides.keys() & {"user", "password", "credential_provider"}:
overrides["credential_provider"] = creds.read_password
else:
@@ -646,6 +665,7 @@ def get_cluster(
satellite_clusters=satellite_clusters,
retry_policy=retry_policy,
connection_overrides=overrides,
+ bootstrap_credential_provider=bootstrap_credential_provider,
)
@@ -699,27 +719,30 @@ class Query:
return f"Query(query={query!r}, parameters={params_repr}, settings={self.settings!r})"
-@dataclass
+@frozen
class RetryPolicy:
max_attempts: int
delay: float | Callable[[int], float]
exceptions: tuple[type[Exception], ...] | Callable[[Exception], bool] = (Exception,)
def __call__(self, fn: Callable[[Client], T]) -> Retryable[T]:
- return Retryable(fn, self)
+ return Retryable(callable=fn, policy=self)
+ def is_retryable(self, e: Exception) -> bool:
+ if isinstance(self.exceptions, tuple):
+ return isinstance(e, self.exceptions)
+ return self.exceptions(e)
-@dataclass
+ def also_retrying(self, predicate: Callable[[Exception], bool]) -> RetryPolicy:
+ return replace(self, exceptions=lambda e: predicate(e) or self.is_retryable(e))
+
+
+@frozen
class Retryable(Generic[T]): # note: this class exists primarily to allow a readable __repr__
callable: Callable[[Client], T]
policy: RetryPolicy
def __call__(self, client: Client) -> T:
- if isinstance(self.policy.exceptions, tuple):
- is_retryable_exception = lambda e: isinstance(e, self.policy.exceptions)
- else:
- is_retryable_exception = self.policy.exceptions
-
if not callable(self.policy.delay):
def delay_fn(_):
@@ -732,7 +755,7 @@ class Retryable(Generic[T]): # note: this class exists primarily to allow a rea
try:
return self.callable(client)
except Exception as e:
- if is_retryable_exception(e) and attempt < self.policy.max_attempts:
+ if self.policy.is_retryable(e) and attempt < self.policy.max_attempts:
delay = delay_fn(attempt)
logger.warning(
"Failed to execute %r (attempt #%s, retry in %0.2fs): %s", self.callable, attempt, delay, e
@@ -750,6 +773,14 @@ class MutationNotFound(Exception):
# not present in clickhouse_driver.errors.ErrorCodes; see ClickHouse src/Common/ErrorCodes.cpp
TOO_MANY_MUTATIONS = 692
+AUTHENTICATION_FAILED = 516
+
+
+def _is_authentication_failure(e: Exception) -> bool:
+ return isinstance(e, ServerException) and e.code == AUTHENTICATION_FAILED
+
+
+_REJECTED_LOGIN_RETRY_POLICY = RetryPolicy(max_attempts=3, delay=5, exceptions=_is_authentication_failure)
@dataclass
diff --git a/posthog/clickhouse/test/test_cluster.py b/posthog/clickhouse/test/test_cluster.py
index 26e230bb5159..fa31870ded04 100644
--- a/posthog/clickhouse/test/test_cluster.py
+++ b/posthog/clickhouse/test/test_cluster.py
@@ -15,6 +15,7 @@ from clickhouse_driver.errors import ServerException
from posthog.clickhouse.client import connection
from posthog.clickhouse.client.connection import ClickHouseCredentials, ClickHouseUser, NodeRole, Workload
from posthog.clickhouse.cluster import (
+ AUTHENTICATION_FAILED,
TOO_MANY_MUTATIONS,
AlterTableMutationRunner,
ClickhouseCluster,
@@ -40,23 +41,23 @@ def cluster(django_db_setup) -> Iterator[ClickhouseCluster]:
@pytest.mark.parametrize(
- "static_password, password_file_set, overrides_arg, expected_bootstrap, expect_provider",
+ "static_password, password_file_set, overrides_arg, expect_token_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, None, True, True, id="dual_armed_default_bootstraps_on_token"),
+ pytest.param("", True, None, True, True, id="token_first_default_bootstraps_on_token"),
+ pytest.param("static-only", False, None, False, False, id="static_default_uses_password"),
pytest.param(
"static-fallback",
True,
{"user": "backups", "password": "bkp-static"},
- "static",
+ True,
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
+def test_get_cluster_bootstraps_a_file_backed_user_on_its_live_token(
+ monkeypatch, tmp_path, static_password, password_file_set, overrides_arg, expect_token_bootstrap, expect_provider
) -> None:
token = "live-token"
token_file = tmp_path / "token"
@@ -75,17 +76,19 @@ def test_get_cluster_keeps_the_bootstrap_off_an_expirable_token(
get_cluster(connection_overrides=overrides_arg)
bootstrap_password = mock_default_client.call_args.kwargs.get("password")
+ bootstrap_provider = mock_cluster.call_args.kwargs["bootstrap_credential_provider"]
overrides = mock_cluster.call_args.kwargs["connection_overrides"]
+ token_file.write_text("rotated-token")
- if expected_bootstrap == "static":
- assert bootstrap_password == static_password
- elif expected_bootstrap == "token":
+ if expect_token_bootstrap:
assert bootstrap_password == token
+ assert bootstrap_provider() == "rotated-token"
else:
assert bootstrap_password is None
+ assert bootstrap_provider is None
if expect_provider:
- assert overrides["credential_provider"]() == token
+ assert overrides["credential_provider"]() == "rotated-token"
else:
assert "credential_provider" not in overrides
@@ -626,6 +629,58 @@ def test_sibling_addresses_another_cluster_and_is_memoized() -> None:
assert cluster.sibling("events") is sibling
+ "credential_provider_set, caller_retry_policy_set, expected_presented",
+ [
+ pytest.param(
+ True, True, ["token-1", "token-2", "token-3"], id="token_bootstrap_presents_a_fresh_token_each_attempt"
+ ),
+ pytest.param(
+ True, False, ["token-1", "token-2", "token-3"], id="token_bootstrap_retries_without_a_caller_policy"
+ ),
+ pytest.param(False, True, ["static"], id="static_bootstrap_fails_on_a_rejected_login"),
+ ],
+)
+def test_discovery_retries_a_rejected_login_only_with_a_fresh_token(
+ credential_provider_set: bool, caller_retry_policy_set: bool, expected_presented: list[str]
+) -> None:
+ hosts_by_cluster = {
+ "posthog": [("host1", 9000, 1, 1, "online", "data")],
+ "events": [("events-host1", 9000, 1, 1, "online", "data")],
+ }
+ presented: list[str] = []
+ bootstrap_client_mock = Mock()
+ bootstrap_client_mock.connection.password = "static"
+
+ def mock_execute(query, params):
+ presented.append(bootstrap_client_mock.connection.password)
+ if len(presented) == 1:
+ raise ServerException("Authentication failed", code=AUTHENTICATION_FAILED)
+ return hosts_by_cluster[params["name"]]
+
+ bootstrap_client_mock.execute = Mock(side_effect=mock_execute)
+ tokens = iter(["token-1", "token-2", "token-3"])
+
+ def discover() -> None:
+ ClickhouseCluster(
+ bootstrap_client_mock,
+ cluster="posthog",
+ retry_policy=RetryPolicy(max_attempts=2, delay=0, exceptions=(TimeoutError,))
+ if caller_retry_policy_set
+ else None,
+ bootstrap_credential_provider=(lambda: next(tokens)) if credential_provider_set else None,
+ ).sibling("events")
+
+ with patch("posthog.clickhouse.cluster.time.sleep"):
+ if credential_provider_set:
+ discover()
+ else:
+ with pytest.raises(ServerException):
+ discover()
+
+ assert presented == expected_presented
+
+
def test_satellite_cluster_hosts_have_no_shard_info() -> None:
bootstrap_client_mock = Mock()
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 79e012d7329f..5a1be045efe0 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -1594,7 +1594,7 @@
8 posthog/temporal/ai_observability/evaluation_clustering/activities.py
8 posthog/temporal/delete_teams/types.py
8 products/signals/backend/temporal/signal_queries.py
-9 posthog/clickhouse/cluster.py
+5 posthog/clickhouse/cluster.py
9 posthog/temporal/backfill_materialized_property/activities.py
9 products/experiments/backend/temporal/models.py
9 products/signals/backend/temporal/reingestion.py