: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(alerts): query clickhouse as per-source alerts platform users (#112846)
Jimmy Zhu5110680c1d87
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.pyindex 51bd4a4d5517..d49421f2027d 100644--- a/posthog/clickhouse/client/connection.py+++ b/posthog/clickhouse/client/connection.py@@ -109,6 +109,11 @@ class ClickHouseUser(StrEnum):# Session replay surfacing scoring sweepSURFACING_SCORING = "surfacing_scoring"DELETION_EXECUTOR = "deletion_executor"+ # The alerts platform's parallel evaluation has one user per source. A source's checks then+ # never take from the concurrency budget of the user that its production alerting queries as.+ ALERTS_PLATFORM_INSIGHT = "alerts_platform_insight"+ # Exists on the logs cluster only. Pass it with Workload.LOGS, never as a query tag.+ ALERTS_PLATFORM_LOGS = "alerts_platform_logs"# Backups - used by Dagster backup jobsBACKUPS = "backups"@@ -224,6 +229,13 @@ def init_clickhouse_users() -> Mapping[ClickHouseUser, ClickHouseCredentials]:return user_dict+def _registered_users() -> Mapping[ClickHouseUser, ClickHouseCredentials]:+ global __user_dict+ if not __user_dict:+ __user_dict = init_clickhouse_users()+ return __user_dict++def get_clickhouse_creds(user: ClickHouseUser) -> ClickHouseCredentials:"""Retrieve ClickHouse credentials for the specified user.@@ -241,10 +253,8 @@ def get_clickhouse_creds(user: ClickHouseUser) -> ClickHouseCredentials:user (ClickHouseUser): The user whose ClickHouse credentials needto be retrieved."""- global __user_dict- if not __user_dict:- __user_dict = init_clickhouse_users()- if creds := __user_dict.get(user):+ users = _registered_users()+ if creds := users.get(user):return credsif user == ClickHouseUser.BUSINESS_KNOWLEDGE:raise RuntimeError(@@ -258,7 +268,7 @@ def get_clickhouse_creds(user: ClickHouseUser) -> ClickHouseCredentials:"CLICKHOUSE_DELETION_EXECUTOR_PASSWORD or ""CLICKHOUSE_DELETION_EXECUTOR_PASSWORD_FILE")- return __user_dict[ClickHouseUser.DEFAULT]+ return users[ClickHouseUser.DEFAULT]@frozen@@ -377,6 +387,25 @@ def get_http_client(**overrides):yield ProxyClient(get_client(**kwargs))+# Named users that exist on the logs cluster. Every other named user exists on the main cluster+# only, and sync_execute assigns some of them (APP, API) from tags without checking the workload.+LOGS_CLUSTER_USERS: frozenset[ClickHouseUser] = frozenset({ClickHouseUser.ALERTS_PLATFORM_LOGS})+++def connection_creds(workload: Workload, ch_user: ClickHouseUser) -> ClickHouseCredentials | None:+ """The credentials a connection authenticates with, or None when it uses the logs cluster's own user.++ A logs connection uses a named user only when the user exists on the logs cluster and is+ registered. get_clickhouse_creds falls back to the default user, whose credentials belong to+ the main cluster.+ """+ if workload != Workload.LOGS:+ return get_clickhouse_creds(ch_user)+ if ch_user not in LOGS_CLUSTER_USERS:+ return None+ return _registered_users().get(ch_user)++def get_kwargs_for_client(workload: Workload = Workload.DEFAULT,team_id=None,@@ -384,13 +413,18 @@ def get_kwargs_for_client(ch_user: ClickHouseUser = ClickHouseUser.DEFAULT,):if workload == Workload.LOGS:- return {+ logs_kwargs = {"host": settings.CLICKHOUSE_LOGS_CLUSTER_HOST,"port": settings.CLICKHOUSE_LOGS_CLUSTER_PORT,"database": settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE,+ "secure": settings.CLICKHOUSE_LOGS_CLUSTER_SECURE,+ }+ if named := connection_creds(workload, ch_user):+ return {**logs_kwargs, "user": named.user, "password": named.password}+ return {+ **logs_kwargs,"user": settings.CLICKHOUSE_LOGS_CLUSTER_USER,"password": settings.CLICKHOUSE_LOGS_CLUSTER_PASSWORD,- "secure": settings.CLICKHOUSE_LOGS_CLUSTER_SECURE,}creds = get_clickhouse_creds(ch_user)@@ -418,11 +452,11 @@ def get_kwargs_for_client(return base_kwargs-def is_file_backed_user(creds: ClickHouseCredentials, workload: Workload, user: str | None) -> bool:+def is_file_backed_user(creds: ClickHouseCredentials, user: str | None) -> bool:# True when the resolved connection authenticates as a user whose credential comes from a- # rotating token file. The LOGS and readonly paths resolve to their own static credentials, so- # they are excluded and keep the static password.- return bool(creds.password_file) and workload != Workload.LOGS and user == creds.user+ # rotating token file. The readonly path resolves to its own static credentials, so it keeps+ # the static password. connection_creds returns None for the logs cluster's own user.+ return bool(creds.password_file) and user == creds.userdef get_http_kwargs(@@ -438,8 +472,8 @@ def get_http_kwargs(on every checkout, which means a read here would only duplicate it on the hot query path."""kwargs = get_kwargs_for_client(workload=workload, team_id=team_id, readonly=readonly, ch_user=ch_user)- creds = get_clickhouse_creds(ch_user)- if is_file_backed_user(creds, workload, kwargs.get("user")):+ creds = connection_creds(workload, ch_user)+ if creds is not None and is_file_backed_user(creds, kwargs.get("user")):kwargs["password"] = creds.read_password()return kwargs@@ -476,10 +510,10 @@ def get_pool(Note that the same pool should be returned every call."""kwargs = get_kwargs_for_client(workload=workload, team_id=team_id, readonly=readonly, ch_user=ch_user)- creds = get_clickhouse_creds(ch_user)+ creds = connection_creds(workload, ch_user)# A file-backed user reads its credential fresh on every checkout, so the pool is keyed on# identity rather than the rotating credential and stamps the credential in RefreshingChPool.pull.- if is_file_backed_user(creds, workload, kwargs.get("user")):+ if creds is not None and is_file_backed_user(creds, kwargs.get("user")):kwargs.pop("password", None)return make_ch_pool(credential_provider=creds.read_password, **kwargs)return make_ch_pool(**kwargs)diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.pyindex 78e5fb64c6a3..857f68c60f9a 100644--- a/posthog/clickhouse/client/execute.py+++ b/posthog/clickhouse/client/execute.py@@ -520,6 +520,8 @@ def sync_execute(# belongs on APP rather than behind a batch concurrency budget. Callers that named a user# keep it, so HogQL's own metadata lookups don't spend the budget meant for real queries.ch_user = ClickHouseUser.LLM_ANALYTICS+ elif ch_user == ClickHouseUser.DEFAULT and tags.ch_user:+ ch_user = ClickHouseUser(tags.ch_user)# To humans and bots reading this, you might be tempted to add a catch-all tag to avoid# hitting this error. Please don't do this. This error is to let us know about queriesdiff --git a/posthog/clickhouse/client/test/test_connection.py b/posthog/clickhouse/client/test/test_connection.pyindex a09010ddb4e1..63f09e8bb61f 100644--- a/posthog/clickhouse/client/test/test_connection.py+++ b/posthog/clickhouse/client/test/test_connection.py@@ -247,3 +247,40 @@ def reset_state():make_ch_pool.cache_clear()set_default_clickhouse_workload_type(Workload.ONLINE)+++ "registered,ch_user,expected_user,expected_password",+ [+ (True, ClickHouseUser.ALERTS_PLATFORM_LOGS, "alerts_platform_logs", "logs-token"),+ (False, ClickHouseUser.ALERTS_PLATFORM_LOGS, "logs-user", "logs-static"),+ (True, ClickHouseUser.DEFAULT, "logs-user", "logs-static"),+ (True, ClickHouseUser.APP, "logs-user", "logs-static"),+ ],+)+def test_logs_workload_uses_a_named_user_only_when_registered(+ settings, monkeypatch, tmp_path, registered, ch_user, expected_user, expected_password+):+ settings.CLICKHOUSE_LOGS_CLUSTER_USER = "logs-user"+ settings.CLICKHOUSE_LOGS_CLUSTER_PASSWORD = "logs-static"+ default_token = tmp_path / "default-token"+ default_token.write_text("default-token")+ logs_token = tmp_path / "logs-token"+ logs_token.write_text("logs-token")+ users = {+ ClickHouseUser.DEFAULT: ClickHouseCredentials(user="default", password="x", password_file=str(default_token))+ }+ if registered:+ users[ClickHouseUser.ALERTS_PLATFORM_LOGS] = ClickHouseCredentials(+ user="alerts_platform_logs", password="fallback", password_file=str(logs_token)+ )+ users[ClickHouseUser.APP] = ClickHouseCredentials(user="app", password="app-static")+ monkeypatch.setattr(connection, "__user_dict", users)++ kwargs = get_http_kwargs(Workload.LOGS, ch_user=ch_user)++ assert (kwargs["host"], kwargs["user"], kwargs["password"]) == (+ settings.CLICKHOUSE_LOGS_CLUSTER_HOST,+ expected_user,+ expected_password,+ )diff --git a/posthog/clickhouse/client/test/test_execute.py b/posthog/clickhouse/client/test/test_execute.pyindex b840e83b7d67..8974e1822435 100644--- a/posthog/clickhouse/client/test/test_execute.py+++ b/posthog/clickhouse/client/test/test_execute.py@@ -102,6 +102,21 @@ def test_llm_analytics_ch_user_routing(client_from_pool, product, kind, tag_id,assert client_from_pool.call_args[0][3] == expected_ch_user+ "tagged_ch_user,requested_ch_user,expected_ch_user",+ [+ (ClickHouseUser.ALERTS_PLATFORM_INSIGHT, ClickHouseUser.DEFAULT, ClickHouseUser.ALERTS_PLATFORM_INSIGHT),+ (None, ClickHouseUser.DEFAULT, ClickHouseUser.DEFAULT),+ (ClickHouseUser.ALERTS_PLATFORM_INSIGHT, ClickHouseUser.META, ClickHouseUser.META),+ ],+)+def test_tagged_ch_user_routing(client_from_pool, tagged_ch_user, requested_ch_user, expected_ch_user):+ with tags_context(product=Product.PRODUCT_ANALYTICS, kind="temporal", id="alerts", ch_user=tagged_ch_user):+ sync_execute("SELECT 1", flush=False, ch_user=requested_ch_user)++ assert client_from_pool.call_args[0][3] == expected_ch_user++@pytest.mark.parametrize("product,expected_slots",[diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.pyindex 2844711dc91e..de0df49776b5 100644--- a/posthog/clickhouse/cluster.py+++ b/posthog/clickhouse/cluster.py@@ -647,7 +647,7 @@ def get_cluster(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):+ if is_file_backed_user(creds, creds.user):bootstrap_credential_provider = creds.read_passwordbootstrap_client = default_client(host=host, password=creds.read_password())if not overrides.keys() & {"user", "password", "credential_provider"}:diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex d126c1788499..71877f2d5927 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -16,7 +16,7 @@ if TYPE_CHECKING:# from posthog.schema_enums import PersonsOnEventsModeimport structlogfrom cachetools import cached-from pydantic import BaseModel, ConfigDict+from pydantic import BaseModel, ConfigDict, field_validatorfrom posthog.schema_enums import NodeKind, ProductKey@@ -421,6 +421,9 @@ class QueryTags(BaseModel):route_id: Optional[str] = Noneworkload: Optional[str] = None # enum connection.Workload+ # The user for a query that names none. sync_execute's product routes (MAX_AI, ENDPOINTS, BILLING,+ # temporal LLM analytics) take precedence over it.+ ch_user: Optional[str] = None # enum connection.ClickHouseUserdashboard_id: Optional[int] = Noneinsight_id: Optional[int] = Nonelookup: Optional[str] = None # a runner's internal lookup before its real query, e.g. "earliest_timestamp"@@ -600,6 +603,16 @@ class QueryTags(BaseModel):model_config = ConfigDict(validate_assignment=True, use_enum_values=True)+ @field_validator("ch_user")+ @classmethod+ def _known_ch_user(cls, value: str | None) -> str | None:+ # Rejected where the tag is set, so a bad value never reaches sync_execute.+ from posthog.clickhouse.client.connection import (+ ClickHouseUser, # noqa: PLC0415 — connection imports this module via posthog.utils+ )++ return None if value is None else ClickHouseUser(value).value+def update(self, **kwargs):for field, value in kwargs.items():setattr(self, field, value)diff --git a/posthog/clickhouse/test/test_query_tagging.py b/posthog/clickhouse/test/test_query_tagging.pyindex 75bf1f3d7ea0..fc0b4e0d13a8 100644--- a/posthog/clickhouse/test/test_query_tagging.py+++ b/posthog/clickhouse/test/test_query_tagging.py@@ -97,10 +97,11 @@ def test_set_get():assert get_query_tag_value("product") == "api"-def test_failure_on_incorrect_type():[email protected]("tags", [{"team_id": "jeden"}, {"ch_user": "alerts_platform_insights"}])+def test_failure_on_incorrect_type(tags):reset_query_tags()with pytest.raises(ValidationError):- tag_queries(team_id="jeden")+ tag_queries(**tags)assert get_query_tags() == create_base_tags()diff --git a/posthog/dags/common/resources.py b/posthog/dags/common/resources.pyindex ce5540a7b84d..6710d690d41e 100644--- a/posthog/dags/common/resources.py+++ b/posthog/dags/common/resources.py@@ -19,7 +19,6 @@ from posthog.clickhouse.backoff import ExponentialBackofffrom posthog.clickhouse.client.connection import (ClickHouseCredentials,ClickHouseUser,- Workload,get_clickhouse_creds,is_file_backed_user,)@@ -74,7 +73,7 @@ def _dedicated_user_connection_overrides(creds: ClickHouseCredentials) -> dict[suntouched, 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):+ if is_file_backed_user(creds, creds.user):overrides["credential_provider"] = creds.read_passwordelse:overrides["password"] = creds.passworddiff --git a/products/logs/backend/alert_check_query.py b/products/logs/backend/alert_check_query.pyindex 3678b792e9b8..127148f5f7c8 100644--- a/products/logs/backend/alert_check_query.py+++ b/products/logs/backend/alert_check_query.py@@ -23,7 +23,7 @@ from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.visitor import CloningVisitor-from posthog.clickhouse.client.connection import Workload+from posthog.clickhouse.client.connection import ClickHouseUser, Workloadfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models import Team@@ -387,6 +387,7 @@ class BatchedAlertCheckQuery:date_to: dt.datetime,projection_eligible: bool | None = None,max_execution_time: int | None = None,+ ch_user: ClickHouseUser = ClickHouseUser.DEFAULT,) -> None:if not alerts:raise ValueError("BatchedAlertCheckQuery requires at least one alert")@@ -396,6 +397,7 @@ class BatchedAlertCheckQuery:self.alerts = list(alerts)self.date_from = date_fromself.date_to = date_to+ self._ch_user = ch_user# A caller that runs several of these inside one deadline needs each query to end before# the deadline does. Throw rather than break: a partial count could resolve an alert that# is actually breaching, and the caller already handles a failed cohort.@@ -570,6 +572,7 @@ class BatchedAlertCheckQuery:query=query,team=self.team,workload=Workload.LOGS,+ ch_user=self._ch_user,settings=self._settings,limit_context=LimitContext.QUERY,modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),@@ -592,7 +595,7 @@ class BatchedAlertCheckQuery:CHECKPOINT_MAX_STALENESS = dt.timedelta(minutes=5)-def fetch_live_logs_checkpoint(team: Team) -> dt.datetime | None:+def fetch_live_logs_checkpoint(team: Team, *, ch_user: ClickHouseUser = ClickHouseUser.DEFAULT) -> dt.datetime | None:tag_queries(product=Product.LOGS,feature=Feature.ALERTING,@@ -604,6 +607,7 @@ def fetch_live_logs_checkpoint(team: Team) -> dt.datetime | None:query=LIVE_LOGS_CHECKPOINT_QUERY,team=team,workload=Workload.LOGS,+ ch_user=ch_user,modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),)if not response.results or response.results[0][0] is None:diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pyindex e9d31d40a310..ebcf7805a335 100644--- a/products/logs/backend/alert_source_cycle.py+++ b/products/logs/backend/alert_source_cycle.py@@ -23,6 +23,7 @@ from uuid import UUIDimport structlog+from posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.dataclasses import frozenfrom posthog.models import Team@@ -456,6 +457,7 @@ def _evaluate_cohort(date_to=date_to,projection_eligible=projection_eligible,max_execution_time=query_seconds,+ ch_user=ClickHouseUser.ALERTS_PLATFORM_LOGS,).execute_rolling_checks(date_to, window_minutes, cadence_minutes, evaluation_periods)except Exception as error:# One cohort's query must not end the batch, which is how the production cohort runner@@ -587,7 +589,7 @@ def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatc# One checkpoint for the pass, matching the production discovery activity. A failure falls# back to wall-clock rather than ending the batch.try:- checkpoint = fetch_live_logs_checkpoint(team)+ checkpoint = fetch_live_logs_checkpoint(team, ch_user=ClickHouseUser.ALERTS_PLATFORM_LOGS)except Exception as error:logger.exception("Failed to fetch logs ingestion checkpoint; falling back to wall-clock", error=str(error))checkpoint = Nonediff --git a/products/notebooks/backend/temporal/frame_materialize.py b/products/notebooks/backend/temporal/frame_materialize.pyindex de9fd2e6d60b..b0eab08801cf 100644--- a/products/notebooks/backend/temporal/frame_materialize.py+++ b/products/notebooks/backend/temporal/frame_materialize.py@@ -657,7 +657,7 @@ def _bounded_offline_client(team_id: int) -> AbstractContextManager:"""kwargs = get_kwargs_for_client(workload=Workload.OFFLINE, team_id=team_id, ch_user=ClickHouseUser.NOTEBOOKS)creds = get_clickhouse_creds(ClickHouseUser.NOTEBOOKS)- if is_file_backed_user(creds, Workload.OFFLINE, kwargs.get("user")):+ if is_file_backed_user(creds, kwargs.get("user")):kwargs.pop("password", None)pool = make_ch_pool(send_receive_timeout=_INSERT_SEND_RECEIVE_TIMEOUT_SECONDS,