: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
fix(notebooks): Increase query scanning limit for notebook nodes and start respecting to the Clickhouse Killswitches (#82660)
Sinan Kucukkoseler6440fe1e3257
diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.pyindex d047a1c3d26a..f7c9981e1c3e 100644--- a/posthog/clickhouse/client/execute.py+++ b/posthog/clickhouse/client/execute.py@@ -207,6 +207,22 @@ def resolve_kill_switch_level(team_id: Optional[int]) -> KillSwitchLevel:return level+def kill_switch_overrides(team_id: Optional[int], ch_user: ClickHouseUser = ClickHouseUser.DEFAULT) -> dict[str, int]:+ """The ClickHouse setting ceilings the kill switch imposes right now, empty when it is off.++ Public because not every path to ClickHouse goes through `sync_execute` — the notebook frame+ materializer streams over raw HTTP and has to apply these itself. Merge with `min()` against+ your own settings, and treat an unset setting as taking the ceiling: the kill switch only+ ever tightens.+ """+ if TEST:+ return {}+ level = resolve_kill_switch_level(team_id)+ if level == KillSwitchLevel.OFF or ch_user in _KILL_SWITCH_EXEMPT_USERS:+ return {}+ return dict(_KILL_SWITCH_SETTINGS[level])++@lru_cache(maxsize=1)def default_settings() -> dict:# https://clickhouse.com/blog/clickhouse-fully-supports-joins-how-to-choose-the-right-algorithm-part5@@ -387,8 +403,8 @@ def sync_execute(}kill_switch_level = KillSwitchLevel.OFF if TEST else resolve_kill_switch_level(team_id)- if kill_switch_level != KillSwitchLevel.OFF and ch_user not in _KILL_SWITCH_EXEMPT_USERS:- overrides = _KILL_SWITCH_SETTINGS[kill_switch_level]+ overrides = kill_switch_overrides(team_id, ch_user)+ if overrides:core_settings.update({k: min(core_settings.get(k, v), v) for k, v in overrides.items()})tags.kill_switch = kill_switch_level.valuediff --git a/products/notebooks/backend/temporal/frame_materialize.py b/products/notebooks/backend/temporal/frame_materialize.pyindex ee3955027da7..7790133e0d13 100644--- a/products/notebooks/backend/temporal/frame_materialize.py+++ b/products/notebooks/backend/temporal/frame_materialize.py@@ -10,8 +10,12 @@ turns it into a 302 to a presigned GET.Load protection mirrors the Celery async path (`process_query_task`): a Redis Luaconcurrency limiter gates activity starts (global + per-team), slot exhaustion and-ClickHouse overload raise retryable errors, and Temporal's retry policy provides the-exponential backoff with a hard schedule-to-close deadline. For a run whose user has the+ClickHouse overload raise retryable errors, Temporal's retry policy provides the+exponential backoff with a hard schedule-to-close deadline, and the ClickHouse kill switch+lowers the per-query caps during an incident on both transports (see `_capped_settings` —+the streaming one needs it because it never passes through sync_execute).++For a run whose user has the`notebooks-frame-store-ch-writes` flag, the query goes to the OFFLINE pool (batch exports'home) as the dedicated `notebooks` ClickHouse user, so a whale materialization contendswith batch work rather than interactive queries, and the user's server-side profile/quota@@ -60,6 +64,7 @@ from posthog.clickhouse.client.connection import (get_kwargs_for_client,make_ch_pool,)+from posthog.clickhouse.client.execute import kill_switch_overridesfrom posthog.clickhouse.client.execute_async import QueryNotFoundError, QueryStatusManager, get_query_statusfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, RateLimitfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context@@ -99,7 +104,9 @@ _SLOT_TTL_SECONDS = 15 * 60# Standing per-query caps, printed into the SQL's SETTINGS clause. max_execution_time is# raised to HOGQL_INCREASED_MAX_EXECUTION_TIME by the NOTEBOOK_MATERIALIZE limit context.-_MAX_BYTES_TO_READ = 50_000_000_000 # 50GB scan budget, the logs-queries precedent+# The scan budget matches the kill switch's most severe ceiling, so a frame is never held to a+# standing limit tighter than the one ClickHouse imposes on everything else during an incident.+_MAX_BYTES_TO_READ = 1_000_000_000_000 # 1TB_MAX_THREADS = 16 # below interactive traffic (the API query-service cap is 60)# Output-side cap (applied as a query setting on the HTTP request): row/scan caps don't# bound the result — `repeat('x', 10000)` over 500k rows makes a ~5GB object from a@@ -316,6 +323,35 @@ def _materialize_slots(team_id: int, task_id: str) -> Iterator[None]:global_limiter.release(global_key, global_task)+def _capped_settings(team_id: int) -> HogQLGlobalSettings:+ """The standing caps, lowered to whatever ceilings the ClickHouse kill switch imposes.++ The streaming transport reaches ClickHouse over raw HTTP, so it never passes through+ sync_execute, which is where every other caller picks the kill switch up. Applying the+ ceilings here stops a frame from being the one notebook query that ignores an incident, and+ makes both transports behave the same whatever the rollout flag says.++ They belong in the printed SETTINGS clause, not in the HTTP params: a query-level SETTINGS+ clause outranks a URL param, so params alone would lose to the caps HogQL prints.++ max_execution_time is the exception. HogQLQueryExecutor raises it to+ HOGQL_INCREASED_MAX_EXECUTION_TIME for this limit context *after* it reads these settings, so+ a ceiling set here is discarded. That is a general HogQL gap rather than a notebook one:+ every HogQL query prints its own max_execution_time, and so outranks the kill switch on+ that one key.+ """+ settings = HogQLGlobalSettings(max_bytes_to_read=_MAX_BYTES_TO_READ, max_threads=_MAX_THREADS)+ for name, ceiling in kill_switch_overrides(team_id).items():+ if name not in type(settings).model_fields:+ # A kill-switch key HogQL has no field for. Running with the remaining ceilings beats+ # failing the frame, but the dropped one must not pass silently.+ logger.warning("notebook_frame_kill_switch_setting_unprintable", setting=name, team_id=team_id)+ continue+ current = getattr(settings, name)+ setattr(settings, name, ceiling if current is None else min(current, ceiling))+ return settings++def _generate_sql(team: Team,user: User | None,@@ -330,7 +366,7 @@ def _generate_sql(user=user,user_access_control=UserAccessControl(user=user, team=team) if user else None,limit_context=LimitContext.NOTEBOOK_MATERIALIZE,- settings=HogQLGlobalSettings(max_bytes_to_read=_MAX_BYTES_TO_READ, max_threads=_MAX_THREADS),+ settings=_capped_settings(team.pk),pretty=False,)if output_format:diff --git a/products/notebooks/backend/test/test_frame_materialize.py b/products/notebooks/backend/test/test_frame_materialize.pyindex e5bb1c069899..0526324f4d24 100644--- a/products/notebooks/backend/test/test_frame_materialize.py+++ b/products/notebooks/backend/test/test_frame_materialize.py@@ -16,6 +16,7 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom posthog.schema import QueryStatus+from posthog.clickhouse.client.execute import _KILL_SWITCH_SETTINGS, KillSwitchLevelfrom posthog.clickhouse.client.execute_async import QueryStatusManagerfrom posthog.errors import ExposedCHQueryError, InternalCHQueryErrorfrom posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQuerySizeExceeded, ClickHouseQueryTimeOut@@ -444,3 +445,26 @@ async def test_exhausted_retries_stop_at_three_scans_and_finalize_the_status():assert attempts == 3assert marked_failed+++class TestFrameMaterializeKillSwitchCaps(APIBaseTest):+ @parameterized.expand(+ [+ ("off", {}),+ ("light", dict(_KILL_SWITCH_SETTINGS[KillSwitchLevel.LIGHT])),+ ("full", dict(_KILL_SWITCH_SETTINGS[KillSwitchLevel.FULL])),+ ]+ )+ def test_printed_sql_carries_kill_switch_ceilings(self, _name: str, overrides: dict[str, int]):+ with patch.object(frame_materialize, "kill_switch_overrides", return_value=overrides):+ sql, _values = frame_materialize._generate_sql(self.team, self.user, "select 1", output_format=None)++ memory_ceiling = overrides.get("max_memory_usage")+ if memory_ceiling is None:+ assert "max_memory_usage" not in sql+ else:+ assert f"max_memory_usage={memory_ceiling}" in sql+ # The lane's own caps already sit under every ceiling, so the merge must keep them+ # rather than widen them to the kill switch's looser numbers.+ assert f"max_threads={frame_materialize._MAX_THREADS}" in sql+ assert f"max_bytes_to_read={frame_materialize._MAX_BYTES_TO_READ}" in sql