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(clickhouse): make notebooks ch-writes pool token-aware (#104552)

Tommy Gilmore9a7f6e6535c6
diff --git a/posthog/clickhouse/client/AGENTS.md b/posthog/clickhouse/client/AGENTS.md
index e6a7483899d9..2a4be381fa2f 100644
--- a/posthog/clickhouse/client/AGENTS.md
+++ b/posthog/clickhouse/client/AGENTS.md
@@ -24,7 +24,7 @@ Token-awareness is lost when you pass your own `sync_client` to `sync_execute`,
Build a custom native pool for a timeout or a setting only by replicating the file-backed branch of `get_pool`.
A pool that skips this branch stays on the static password with no error.
Resolve the credentials with `get_clickhouse_creds`.
-When `_is_file_backed_user` is true, pop the static `password` and pass `credential_provider=creds.read_password` to `make_ch_pool`.
+When `is_file_backed_user` is true, pop the static `password` and pass `credential_provider=creds.read_password` to `make_ch_pool`.
`read_password` reads the token file on each call.
It falls back to the static password when the file is unreadable or empty.
For a user that keeps a static password, it also falls back when the token has expired or is about to expire.
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.py
index 95bc7b783f36..ac2441fe7e30 100644
--- a/posthog/clickhouse/client/connection.py
+++ b/posthog/clickhouse/client/connection.py
@@ -410,7 +410,7 @@ 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, workload: Workload, 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.
@@ -431,7 +431,7 @@ def get_http_kwargs(
"""
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")):
+ if is_file_backed_user(creds, workload, kwargs.get("user")):
kwargs["password"] = creds.read_password()
return kwargs
@@ -471,7 +471,7 @@ def get_pool(
creds = get_clickhouse_creds(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 is_file_backed_user(creds, workload, 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/products/notebooks/backend/temporal/frame_materialize.py b/products/notebooks/backend/temporal/frame_materialize.py
index 841e3474ca2f..8205c5bd2d78 100644
--- a/products/notebooks/backend/temporal/frame_materialize.py
+++ b/products/notebooks/backend/temporal/frame_materialize.py
@@ -64,6 +64,7 @@ from posthog.clickhouse.client.connection import (
ClickHouseUser,
get_clickhouse_creds,
get_kwargs_for_client,
+ is_file_backed_user,
make_ch_pool,
)
from posthog.clickhouse.client.execute import kill_switch_overrides
@@ -645,13 +646,26 @@ def _bounded_offline_client(team_id: int) -> AbstractContextManager:
thread. Route through a dedicated pool that shares the offline-host + notebooks-user
routing but caps the socket timeout just above max_execution_time. `make_ch_pool` is
cached, so this is one extra pool per (offline, notebooks) combination, not per call.
- (Note: sync_execute enters the client as its own context manager and disconnects it on
- exit, so connections aren't kept warm across calls — the pool's value here is the bounded
- timeout, not connection reuse. Negligible at this path's volume: one reconnect per
- materialization, dwarfed by the INSERT itself.)
+ sync_execute enters the client as its own context manager and disconnects it on exit,
+ so connections aren't kept warm across calls. The pool's value here is the bounded
+ timeout, not connection reuse. This costs one reconnect per materialization, which is
+ dwarfed by the INSERT itself.
+
+ Mirror the file-backed branch of `get_pool` so a token-authenticated notebooks user
+ stays token-aware. Without `credential_provider` the pool binds with the static
+ password and never picks up a rotated token.
"""
kwargs = get_kwargs_for_client(workload=Workload.OFFLINE, team_id=team_id, ch_user=ClickHouseUser.NOTEBOOKS)
- pool = make_ch_pool(send_receive_timeout=_INSERT_SEND_RECEIVE_TIMEOUT_SECONDS, **kwargs)
+ creds = get_clickhouse_creds(ClickHouseUser.NOTEBOOKS)
+ if is_file_backed_user(creds, Workload.OFFLINE, kwargs.get("user")):
+ kwargs.pop("password", None)
+ pool = make_ch_pool(
+ send_receive_timeout=_INSERT_SEND_RECEIVE_TIMEOUT_SECONDS,
+ credential_provider=creds.read_password,
+ **kwargs,
+ )
+ else:
+ pool = make_ch_pool(send_receive_timeout=_INSERT_SEND_RECEIVE_TIMEOUT_SECONDS, **kwargs)
return pool.get_client()
diff --git a/products/notebooks/backend/test/test_frame_materialize.py b/products/notebooks/backend/test/test_frame_materialize.py
index 94447aff0b37..7bf09de36a73 100644
--- a/products/notebooks/backend/test/test_frame_materialize.py
+++ b/products/notebooks/backend/test/test_frame_materialize.py
@@ -20,6 +20,8 @@ from posthog.schema import QueryStatus
from posthog.hogql.database.database import Database
from posthog.hogql.parser import parse_select
+from posthog.clickhouse.client import connection
+from posthog.clickhouse.client.connection import ClickHouseCredentials, ClickHouseUser
from posthog.clickhouse.client.execute import _KILL_SWITCH_SETTINGS, KillSwitchLevel
from posthog.clickhouse.client.execute_async import QueryStatusManager
from posthog.errors import ExposedCHQueryError, InternalCHQueryError
@@ -548,3 +550,27 @@ class TestFrameMaterializePrintPasses(APIBaseTest):
)
assert printed.resolve_seconds > 0
+
+
[email protected]("file_backed", [True, False])
+def test_bounded_offline_client_stays_token_aware_for_a_file_backed_user(monkeypatch, tmp_path, file_backed):
+ token = tmp_path / "token"
+ token.write_text("notebooks-token")
+ creds = ClickHouseCredentials(
+ user="notebooks",
+ password="static-fallback",
+ password_file=str(token) if file_backed else None,
+ )
+ monkeypatch.setattr(connection, "__user_dict", {ClickHouseUser.NOTEBOOKS: creds})
+
+ with patch.object(frame_materialize, "make_ch_pool") as mock_pool:
+ frame_materialize._bounded_offline_client(team_id=1)
+
+ call_kwargs = mock_pool.call_args.kwargs
+ assert call_kwargs["send_receive_timeout"] == frame_materialize._INSERT_SEND_RECEIVE_TIMEOUT_SECONDS
+ if file_backed:
+ assert call_kwargs["credential_provider"]() == "notebooks-token"
+ assert "password" not in call_kwargs
+ else:
+ assert call_kwargs["password"] == "static-fallback"
+ assert "credential_provider" not in call_kwargs