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(hogql): compare SQL on an eligible native events cluster (#115591)

Vasco de Krijger29a6e0088e06
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 2d23deff1696..2812bff9496c 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -30366,6 +30366,10 @@
"useMaterializedViews": {
"type": "boolean"
},
+ "useNewEventsCluster": {
+ "description": "Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported.",
+ "type": "boolean"
+ },
"useNewEventsSchema": {
"description": "Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it.",
"type": "boolean"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 43401134ccc2..843fca339ff4 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -545,6 +545,8 @@ export interface HogQLQueryModifiers {
useMaterializedViews?: boolean
/** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */
useNewEventsSchema?: boolean
+ /** Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported. */
+ useNewEventsCluster?: boolean
customChannelTypeRules?: CustomChannelRule[]
customBotDefinitions?: CustomBotRule[]
/** Do not treat a missing user agent as automation on cookieless events. Positive bot signals and custom project rules still apply. Resolved server-side; not intended to be set by clients. */
diff --git a/posthog/api/instance_settings.py b/posthog/api/instance_settings.py
index 112d9143649e..726cc1e94f7e 100644
--- a/posthog/api/instance_settings.py
+++ b/posthog/api/instance_settings.py
@@ -124,6 +124,14 @@ class InstanceSettingsSerializer(serializers.Serializer):
editable = serializers.BooleanField(read_only=True)
is_secret = serializers.BooleanField(read_only=True)
+ def validate_value(self, value: Any) -> Any:
+ if self.instance is not None and self.instance.key == "CLICKHOUSE_NATIVE_EVENTS_HOST":
+ if not isinstance(value, str) or (value and not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.-]{0,252}", value)):
+ raise serializers.ValidationError(
+ "Enter a hostname without a scheme, port or path, or leave it empty to disable the route."
+ )
+ return value
+
def update(self, instance: InstanceSettingHelper, validated_data: dict[str, Any]) -> InstanceSettingHelper:
if instance.key not in SETTINGS_ALLOWING_API_OVERRIDE:
raise serializers.ValidationError("This setting cannot be updated from the API.", code="no_api_override")
diff --git a/posthog/api/team/team_serializer.py b/posthog/api/team/team_serializer.py
index 58242a58d8c8..f1d81f05d302 100644
--- a/posthog/api/team/team_serializer.py
+++ b/posthog/api/team/team_serializer.py
@@ -844,7 +844,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
# The native JSON events table is an internal rollout switch that PostHog staff set per project in Django
# admin. Dropping the key keeps a client from setting or clearing it, including a settings page that echoes
# the whole modifiers dict back.
- value = {key: item for key, item in value.items() if key != "useNewEventsSchema"}
+ value = {key: item for key, item in value.items() if key not in {"useNewEventsSchema", "useNewEventsCluster"}}
if "bounceRateDurationSeconds" in value:
bounce_rate = value["bounceRateDurationSeconds"]
diff --git a/posthog/api/test/test_instance_settings.py b/posthog/api/test/test_instance_settings.py
index dac857ba3d39..8c486879eb3d 100644
--- a/posthog/api/test/test_instance_settings.py
+++ b/posthog/api/test/test_instance_settings.py
@@ -5,6 +5,7 @@ from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.core import mail
+from django.test import SimpleTestCase
from parameterized import parameterized
from rest_framework import status
@@ -12,6 +13,8 @@ from rest_framework import status
from posthog.api.instance_settings import (
REDACTED,
UNSET,
+ InstanceSettingHelper,
+ InstanceSettingsSerializer,
_redact_if_secret,
cast_str_to_desired_type,
get_instance_setting as get_instance_setting_helper,
@@ -108,6 +111,25 @@ class TestSecretSettingsCoverage(unittest.TestCase):
self.assertEqual(_redact_if_secret("EMAIL_HOST", value), value)
+class TestHostSettingValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("native.example.com", True),
+ ("localhost", True),
+ ("", True),
+ ("https://native.example.com", False),
+ ("native.example.com:8443", False),
+ ("native.example.com/path", False),
+ (True, False),
+ ]
+ )
+ def test_host_setting_accepts_hostnames_only(self, value: object, valid: bool) -> None:
+ serializer = InstanceSettingsSerializer(
+ instance=InstanceSettingHelper(key="CLICKHOUSE_NATIVE_EVENTS_HOST"), data={"value": value}, partial=True
+ )
+ self.assertEqual(serializer.is_valid(), valid, serializer.errors)
+
+
class TestInstanceSettings(APIBaseTest):
def setUp(self):
super().setUp()
@@ -190,17 +212,24 @@ class TestInstanceSettings(APIBaseTest):
self.permission_denied_response("You are not a staff user, contact your instance admin."),
)
- def test_update_setting(self):
- response = self.client.get(f"/api/instance_settings/AUTO_START_ASYNC_MIGRATIONS")
+ @parameterized.expand(
+ [
+ ("AUTO_START_ASYNC_MIGRATIONS", False, True),
+ ("CLICKHOUSE_NATIVE_EVENTS_TEAMS", [], [44]),
+ ("CLICKHOUSE_NATIVE_EVENTS_HOST", "", "native.example.com"),
+ ]
+ )
+ def test_update_setting(self, key: str, before: object, after: object) -> None:
+ response = self.client.get(f"/api/instance_settings/{key}")
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["value"], False)
+ self.assertEqual(response.json()["value"], before)
- response = self.client.patch(f"/api/instance_settings/AUTO_START_ASYNC_MIGRATIONS", {"value": True})
+ response = self.client.patch(f"/api/instance_settings/{key}", {"value": after}, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["value"], True)
+ self.assertEqual(response.json()["value"], after)
- self.assertEqual(get_instance_setting_helper("AUTO_START_ASYNC_MIGRATIONS").value, True)
- self.assertEqual(get_instance_setting("AUTO_START_ASYNC_MIGRATIONS"), True)
+ self.assertEqual(get_instance_setting_helper(key).value, after)
+ self.assertEqual(get_instance_setting(key), after)
def test_updating_email_settings(self):
set_instance_setting("EMAIL_HOST", "localhost")
@@ -274,19 +303,26 @@ class TestInstanceSettings(APIBaseTest):
)
self.assertEqual(get_instance_setting("MATERIALIZED_COLUMNS_ENABLED"), True)
- def test_non_staff_user_cant_update(self):
+ @parameterized.expand(
+ [
+ ("AUTO_START_ASYNC_MIGRATIONS", False, True),
+ ("CLICKHOUSE_NATIVE_EVENTS_TEAMS", [], [44]),
+ ("CLICKHOUSE_NATIVE_EVENTS_HOST", "", "native.example.com"),
+ ]
+ )
+ def test_non_staff_user_cant_update(self, key: str, before: object, after: object) -> None:
self.user.is_staff = False
self.user.save()
- response = self.client.get(f"/api/instance_settings/AUTO_START_ASYNC_MIGRATIONS", {"value": True})
+ response = self.client.patch(f"/api/instance_settings/{key}", {"value": after}, format="json")
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(
response.json(),
self.permission_denied_response("You are not a staff user, contact your instance admin."),
)
- self.assertEqual(get_instance_setting_helper("AUTO_START_ASYNC_MIGRATIONS").value, False)
- self.assertEqual(get_instance_setting("AUTO_START_ASYNC_MIGRATIONS"), False)
+ self.assertEqual(get_instance_setting_helper(key).value, before)
+ self.assertEqual(get_instance_setting(key), before)
@parameterized.expand(
[
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 1511778c19c1..8de8a4b2f0bc 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -1406,22 +1406,23 @@ def team_api_test_factory():
{"id": "test", "channel_type": "Direct", "combiner": "AND", "items": []}
]
- def test_modifiers_use_new_events_schema_is_not_client_writable(self) -> None:
+ @parameterized.expand([("useNewEventsSchema",), ("useNewEventsCluster",)])
+ def test_events_routing_modifiers_are_not_client_writable(self, modifier: str) -> None:
response = self.client.patch(
f"/api/environments/{self.team.id}",
- {"modifiers": {"useNewEventsSchema": True}},
+ {"modifiers": {modifier: True}},
)
assert response.status_code == status.HTTP_200_OK, response.json()
- assert "useNewEventsSchema" not in response.json()["modifiers"]
+ assert modifier not in response.json()["modifiers"]
- self.team.modifiers = {"useNewEventsSchema": True}
+ self.team.modifiers = {modifier: True}
self.team.save()
response = self.client.patch(
f"/api/environments/{self.team.id}",
- {"modifiers": {"useNewEventsSchema": False, "bounceRateDurationSeconds": 30}},
+ {"modifiers": {modifier: False, "bounceRateDurationSeconds": 30}},
)
assert response.status_code == status.HTTP_200_OK, response.json()
- assert response.json()["modifiers"] == {"useNewEventsSchema": True, "bounceRateDurationSeconds": 30}
+ assert response.json()["modifiers"] == {modifier: True, "bounceRateDurationSeconds": 30}
@parameterized.expand(
[
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.py
index 49773103d3ea..c212fbd8cc3d 100644
--- a/posthog/clickhouse/client/connection.py
+++ b/posthog/clickhouse/client/connection.py
@@ -430,6 +430,18 @@ def get_kwargs_for_client(
creds = get_clickhouse_creds(ch_user)
base_kwargs = {"user": creds.user, "password": creds.password}
+ if workload == Workload.NEW_EVENTS_CLUSTER:
+ from posthog.models.event.new_events_schema import get_new_events_cluster_host # noqa: PLC0415
+
+ host = get_new_events_cluster_host()
+ if not host:
+ raise ValueError("Native events ClickHouse host is not configured")
+ return {
+ **get_kwargs_for_client(Workload.DEFAULT, team_id, readonly, ch_user),
+ "host": host,
+ "verify": settings.CLICKHOUSE_VERIFY,
+ }
+
if team_id is not None and str(team_id) in settings.CLICKHOUSE_PER_TEAM_SETTINGS:
user_settings = settings.CLICKHOUSE_PER_TEAM_SETTINGS[str(team_id)]
return {**base_kwargs, **user_settings}
diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.py
index 857f68c60f9a..46d15eaace78 100644
--- a/posthog/clickhouse/client/execute.py
+++ b/posthog/clickhouse/client/execute.py
@@ -463,7 +463,7 @@ def sync_execute(
workload = Workload.OFFLINE if is_api_key_auth else Workload.ONLINE
ch_user = ClickHouseUser.API if is_api_key_auth else ClickHouseUser.APP
- if tags.workload == Workload.ENDPOINTS and workload != Workload.LOGS:
+ if tags.workload == Workload.ENDPOINTS and workload not in (Workload.LOGS, Workload.NEW_EVENTS_CLUSTER):
workload = Workload.ENDPOINTS
if workload == Workload.DEFAULT:
diff --git a/posthog/clickhouse/client/test/test_connection.py b/posthog/clickhouse/client/test/test_connection.py
index 63f09e8bb61f..c00d712b6d30 100644
--- a/posthog/clickhouse/client/test/test_connection.py
+++ b/posthog/clickhouse/client/test/test_connection.py
@@ -89,6 +89,51 @@ def test_connection_pool_creation_with_team_id(settings):
assert team_pool.connection_args["host"] == "clicky"
+def test_native_events_pool_is_separate_from_legacy_pool(settings, monkeypatch):
+ from posthog.hogql_queries.utils.parallel import run_in_parallel_threads
+ from posthog.models.event.new_events_schema import new_events_cluster_host_scope
+
+ settings.CLICKHOUSE_NATIVE_EVENTS_HOST = "env.example.com"
+ host = "native.example.com"
+ monkeypatch.setattr("posthog.models.event.new_events_schema.get_instance_setting", lambda key: host)
+ settings.CLICKHOUSE_VERIFY = True
+ settings.CLICKHOUSE_PER_TEAM_SETTINGS = {}
+ legacy = get_pool(Workload.ONLINE, team_id=44)
+ native = get_pool(Workload.NEW_EVENTS_CLUSTER, team_id=44)
+ assert native is not legacy
+ assert native.connection_args["host"] == "native.example.com"
+ with new_events_cluster_host_scope():
+ assert get_pool(Workload.NEW_EVENTS_CLUSTER, team_id=44) is native
+ host = "replacement.example.com"
+ pools = []
+ run_in_parallel_threads([lambda: pools.append(get_pool(Workload.NEW_EVENTS_CLUSTER, team_id=44))])
+ assert pools == [native]
+ replacement = get_pool(Workload.NEW_EVENTS_CLUSTER, team_id=44)
+ assert replacement is not native
+ assert replacement.connection_args["host"] == host
+
+
[email protected]("readonly", [False, True])
[email protected]("team_override", [False, True])
+def test_native_events_route_preserves_resolved_credentials(settings, readonly, team_override):
+ settings.CLICKHOUSE_NATIVE_EVENTS_HOST = "native.example.com"
+ settings.CLICKHOUSE_VERIFY = True
+ settings.CLICKHOUSE_PER_TEAM_SETTINGS = (
+ {"44": {"host": "legacy.example.com", "user": "team-user", "password": "example"}} if team_override else {}
+ )
+ settings.READONLY_CLICKHOUSE_USER = "reader"
+ settings.READONLY_CLICKHOUSE_PASSWORD = "example-readonly"
+ baseline = connection.get_kwargs_for_client(Workload.DEFAULT, team_id=44, readonly=readonly)
+ native = connection.get_kwargs_for_client(Workload.NEW_EVENTS_CLUSTER, team_id=44, readonly=readonly)
+ assert native == {**baseline, "host": "native.example.com", "verify": True}
+
+
+def test_native_events_workload_without_host_fails_closed(settings):
+ settings.CLICKHOUSE_NATIVE_EVENTS_HOST = None
+ with pytest.raises(ValueError, match="Native events ClickHouse host is not configured"):
+ get_pool(Workload.NEW_EVENTS_CLUSTER)
+
+
def test_read_password_reads_file_fresh_and_stripped(tmp_path):
token = tmp_path / "token"
token.write_text("tok-0\n")
@@ -178,29 +223,33 @@ def test_deletion_executor_credentials_do_not_fall_back_to_default(monkeypatch):
get_clickhouse_creds(ClickHouseUser.DELETION_EXECUTOR)
-def test_file_backed_pool_is_stable_across_credential_rotation(settings, monkeypatch, tmp_path):
[email protected]("workload", [Workload.ONLINE, Workload.NEW_EVENTS_CLUSTER])
+def test_file_backed_pool_is_stable_across_credential_rotation(settings, monkeypatch, tmp_path, workload):
+ settings.CLICKHOUSE_NATIVE_EVENTS_HOST = "native.example.com"
settings.CLICKHOUSE_OFFLINE_CLUSTER_HOST = None
token = tmp_path / "token"
token.write_text("tok-0")
_file_backed_default(monkeypatch, token)
- pool = get_pool(Workload.ONLINE)
+ pool = get_pool(workload)
assert isinstance(pool, RefreshingChPool)
token.write_text("tok-1") # rotate the projected token in place
- assert get_pool(Workload.ONLINE) is pool
+ assert get_pool(workload) is pool
assert make_ch_pool.cache_info().currsize == 1
-def test_get_http_kwargs_reads_file_backed_credential_fresh(monkeypatch, tmp_path):
[email protected]("workload", [Workload.ONLINE, Workload.NEW_EVENTS_CLUSTER])
+def test_get_http_kwargs_reads_file_backed_credential_fresh(settings, monkeypatch, tmp_path, workload):
+ settings.CLICKHOUSE_NATIVE_EVENTS_HOST = "native.example.com"
token = tmp_path / "token"
token.write_text("tok-0")
_file_backed_default(monkeypatch, token)
- assert get_http_kwargs(Workload.ONLINE)["password"] == "tok-0"
+ assert get_http_kwargs(workload)["password"] == "tok-0"
token.write_text("tok-1") # a rotation must reach the short-lived HTTP client, not a value cached at build
- assert get_http_kwargs(Workload.ONLINE)["password"] == "tok-1"
+ assert get_http_kwargs(workload)["password"] == "tok-1"
def test_get_client_from_pool_http_branch_sends_fresh_token(settings, monkeypatch, tmp_path):
@@ -240,8 +289,12 @@ def test_refreshing_pool_stamps_current_credential(tmp_path):
@pytest.fixture(autouse=True)
-def reset_state():
+def reset_state(settings, monkeypatch):
make_ch_pool.cache_clear()
+ monkeypatch.setattr(
+ "posthog.models.event.new_events_schema.get_instance_setting",
+ lambda key: settings.CLICKHOUSE_NATIVE_EVENTS_HOST,
+ )
yield
@@ -284,3 +337,34 @@ def test_logs_workload_uses_a_named_user_only_when_registered(
expected_user,
expected_password,
)
+
+
+ "workload,clickhouse_verify,queryservice_verify,expected_verify",
+ [
+ (Workload.NEW_EVENTS_CLUSTER, False, True, True),
+ (Workload.NEW_EVENTS_CLUSTER, True, False, False),
+ (Workload.OFFLINE, True, True, True),
+ ],
+)
+def test_http_pool_preserves_existing_verification_policy(
+ settings, monkeypatch, workload, clickhouse_verify, queryservice_verify, expected_verify
+):
+ settings.CLICKHOUSE_NATIVE_EVENTS_HOST = "native.example.com"
+ settings.CLICKHOUSE_OFFLINE_CLUSTER_HOST = "offline.example.com"
+ settings.CLICKHOUSE_VERIFY = clickhouse_verify
+ settings.QUERYSERVICE_VERIFY = queryservice_verify
+ settings.CLICKHOUSE_SECURE = True
+ settings.CLICKHOUSE_LOGS_CLUSTER_SECURE = True
+ settings.CLICKHOUSE_USE_HTTP = True
+ monkeypatch.setattr(connection, "_default_workload", Workload.OFFLINE)
+ connection._clickhouse_http_pool_mgr.cache_clear()
+ try:
+ with patch("clickhouse_connect.get_client") as client:
+ with connection.get_client_from_pool(workload):
+ pass
+ manager = client.call_args.kwargs["pool_mgr"]
+ assert client.call_args.kwargs["secure"]
+ assert manager.connection_pool_kw["cert_reqs"] == ("CERT_REQUIRED" if expected_verify else "CERT_NONE")
+ finally:
+ connection._clickhouse_http_pool_mgr.cache_clear()
diff --git a/posthog/clickhouse/client/test/test_execute.py b/posthog/clickhouse/client/test/test_execute.py
index 8974e1822435..e1896d81fbed 100644
--- a/posthog/clickhouse/client/test/test_execute.py
+++ b/posthog/clickhouse/client/test/test_execute.py
@@ -69,6 +69,7 @@ def test_process_query_task_workload_routing(
[
(Workload.DEFAULT, Workload.ENDPOINTS),
(Workload.LOGS, Workload.LOGS),
+ (Workload.NEW_EVENTS_CLUSTER, Workload.NEW_EVENTS_CLUSTER),
],
)
def test_endpoints_tag_workload_routing(client_from_pool, workload, expected_workload):
diff --git a/posthog/clickhouse/workload.py b/posthog/clickhouse/workload.py
index ff0897bb464c..24cc9db7cb9b 100644
--- a/posthog/clickhouse/workload.py
+++ b/posthog/clickhouse/workload.py
@@ -10,5 +10,6 @@ class Workload(StrEnum):
OFFLINE = "OFFLINE"
# Logs queries
LOGS = "LOGS"
+ NEW_EVENTS_CLUSTER = "NEW_EVENTS_CLUSTER"
# Endpoints (the product) queries
ENDPOINTS = "ENDPOINTS"
diff --git a/posthog/hogql/modifiers.py b/posthog/hogql/modifiers.py
index dd844202a21e..23af691149a1 100644
--- a/posthog/hogql/modifiers.py
+++ b/posthog/hogql/modifiers.py
@@ -58,11 +58,23 @@ def create_default_modifiers_for_team(
else:
modifiers = modifiers.model_copy()
+ from posthog.models.event.new_events_schema import use_new_events_cluster # noqa: PLC0415
+
+ if use_new_events_cluster(team.pk, modifiers):
+ if modifiers.useNewEventsSchema is False:
+ from posthog.hogql.errors import ExposedHogQLError # noqa: PLC0415
+
+ raise ExposedHogQLError("Native events cluster queries require the native events schema.")
+ modifiers.useNewEventsSchema = True
+
if modifiers.useMaterializedViews is None:
modifiers.useMaterializedViews = True
if isinstance(team.modifiers, dict):
for key, value in team.modifiers.items():
+ # Cluster routing requires a query opt-in, even if a project stores the modifier.
+ if key == "useNewEventsCluster":
+ continue
if getattr(modifiers, key, None) is None:
if key == "customChannelTypeRules":
# don't break all queries if customChannelTypeRules are invalid
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index 783cfe05ba37..fc720999ecc2 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -69,10 +69,11 @@ from posthog.hogql.warehouse_warnings import record_warnings
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import ClickHouseUser, Workload
-from posthog.clickhouse.query_tagging import get_query_tag_value, get_query_tags, tag_queries
+from posthog.clickhouse.query_tagging import Product, get_query_tag_value, get_query_tags, tag_queries
from posthog.dataclasses import frozen
from posthog.direct_query_cancellation import build_direct_query_cancellation_token
from posthog.errors import CHQueryErrorS3Error, CHQueryErrorS3FileChangedDuringRead, ExposedCHQueryError
+from posthog.models.event.new_events_schema import new_events_cluster_host_scope, use_new_events_cluster
from posthog.models.team import Team
from posthog.models.user import User
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
@@ -160,6 +161,8 @@ class HogQLQueryExecutor:
self.context.user_access_control = self.user_access_control
self.query_modifiers = create_default_modifiers_for_team(self.team, self.modifiers)
+ if self.connection_id and self.query_modifiers.useNewEventsCluster:
+ raise ExposedHogQLError("Native events cluster queries cannot use a warehouse connection.")
self.debug = self.modifiers is not None and self.modifiers.debug
self.error: Optional[str] = None
self.explain: Optional[list[str]] = None
@@ -245,6 +248,8 @@ class HogQLQueryExecutor:
@tracer.start_as_current_span("HogQLQueryExecutor._apply_optimizers")
def _apply_optimizers(self):
+ if self.query_modifiers.useNewEventsCluster:
+ return
if self.query_modifiers.usePreaggregatedTableTransforms:
with self.timings.measure("preaggregated_table_transforms"):
assert self.hogql_context is not None
@@ -939,6 +944,19 @@ class HogQLQueryExecutor:
workload = self.workload
if workload == Workload.DEFAULT and clickhouse_context.workload is not None:
workload = clickhouse_context.workload
+ if use_new_events_cluster(self.team.pk, self.query_modifiers):
+ if get_query_tags().product == Product.ENDPOINTS or workload not in (
+ Workload.DEFAULT,
+ Workload.ONLINE,
+ Workload.OFFLINE,
+ Workload.NEW_EVENTS_CLUSTER,
+ ):
+ raise ExposedHogQLError(
+ "New events cluster opt-ins support analytics workloads only. Remove useNewEventsCluster for logs or endpoints queries."
+ )
+ if not clickhouse_context.uses_new_events_schema():
+ raise ExposedHogQLError("New events cluster queries require the native events schema.")
+ workload = Workload.NEW_EVENTS_CLUSTER
def run_clickhouse_query() -> Any:
return sync_execute(
@@ -1030,6 +1048,7 @@ class HogQLQueryExecutor:
)
@tracer.start_as_current_span("HogQLQueryExecutor.execute")
+ @new_events_cluster_host_scope()
def execute(self) -> HogQLQueryResponse:
self._executing = True
trace.get_current_span().set_attribute("team_id", self.team.pk)
diff --git a/posthog/hogql/test/test_modifiers.py b/posthog/hogql/test/test_modifiers.py
index 3cabffbb3789..85305261405b 100644
--- a/posthog/hogql/test/test_modifiers.py
+++ b/posthog/hogql/test/test_modifiers.py
@@ -80,10 +80,14 @@ class TestModifiers(BaseTest):
== PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED # no change here
)
- self.team.modifiers = {"personsOnEventsMode": PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS}
+ self.team.modifiers = {
+ "personsOnEventsMode": PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS,
+ "useNewEventsCluster": True,
+ }
self.team.save()
modifiers = create_default_modifiers_for_team(self.team)
assert modifiers.personsOnEventsMode == PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS
+ assert modifiers.useNewEventsCluster is None
def test_unparseable_custom_bot_definitions_are_dropped(self):
# modifiers is hand-editable JSON (e.g. Django admin), so an entry that is not a rule object
diff --git a/posthog/hogql/test/test_new_events_schema_routing.py b/posthog/hogql/test/test_new_events_schema_routing.py
new file mode 100644
index 000000000000..ab27e2c45ac9
--- /dev/null
+++ b/posthog/hogql/test/test_new_events_schema_routing.py
@@ -0,0 +1,220 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.schema import HogQLQuery, HogQLQueryModifiers, PersonsOnEventsMode
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.query import HogQLQueryExecutor
+
+from posthog.clickhouse.query_tagging import Product, tags_context
+from posthog.clickhouse.workload import Workload
+from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner
+from posthog.models import Organization, Team, User
+from posthog.models.instance_setting import override_instance_config
+
+
+@override_settings(CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA=False, CLICKHOUSE_NATIVE_EVENTS_HOST="native.example.com")
+class TestNewEventsClusterRouting(SimpleTestCase):
+ def setUp(self) -> None:
+ self.team = Team(id=44, modifiers={}, organization=Organization(id=1))
+ self.user = User(id=123, is_staff=True, is_active=True)
+ self.modifiers = HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.DISABLED)
+ self.instance_settings: dict[str, object] = {
+ "CLICKHOUSE_NATIVE_EVENTS_TEAMS": [44],
+ "CLICKHOUSE_NATIVE_EVENTS_HOST": "native.example.com",
+ }
+ self.enterContext(
+ patch("posthog.models.event.new_events_schema.get_instance_setting", self.instance_settings.get)
+ )
+ self.enterContext(
+ patch(
+ "products.web_analytics.backend.hogql_queries.cookieless_flag.resolve_cookieless_traffic_is_regular_modifier",
+ return_value=True,
+ )
+ )
+
+ @parameterized.expand(
+ [
+ ([], "native.example.com", "not enabled"),
+ ([44, True], "native.example.com", "not enabled"),
+ ([44], None, "host is not configured"),
+ ]
+ )
+ def test_unavailable_native_route_fails_closed(self, allowed: object, host: str | None, error: str) -> None:
+ self.instance_settings.update(CLICKHOUSE_NATIVE_EVENTS_HOST=host, CLICKHOUSE_NATIVE_EVENTS_TEAMS=allowed)
+ with self.assertRaisesRegex(ExposedHogQLError, error):
+ HogQLQueryRunner(
+ query=HogQLQuery(
+ query="SELECT 1", modifiers=self.modifiers.model_copy(update={"useNewEventsCluster": True})
+ ),
+ team=self.team,
+ )
+
+ def test_direct_warehouse_connection_cannot_claim_native_cluster_opt_in(self) -> None:
+ with self.assertRaisesRegex(ExposedHogQLError, "warehouse connection"):
+ HogQLQueryExecutor(
+ query="SELECT 1",
+ team=self.team,
+ modifiers=self.modifiers.model_copy(update={"useNewEventsCluster": True}),
+ connection_id="example-connection",
+ )
+
+ @parameterized.expand([(False,), (True,)])
+ def test_native_cache_identity_tracks_host_configuration_without_changing_legacy_namespace(
+ self, native: bool
+ ) -> None:
+ runner = HogQLQueryRunner(
+ query=HogQLQuery(
+ query="SELECT 1",
+ modifiers=self.modifiers.model_copy(
+ update={"useNewEventsSchema": native, "useNewEventsCluster": native}
+ ),
+ ),
+ team=self.team,
+ )
+ with (
+ patch.object(runner, "_get_property_access_restrictions", return_value=None),
+ patch.object(runner, "_products_modifiers_for_cache", return_value={}),
+ patch("posthog.hogql_queries.query_runner.events_retention_months_for_team", return_value=None),
+ ):
+ keys = []
+ for host in ("native.example.com", "replacement.example.com"):
+ self.instance_settings["CLICKHOUSE_NATIVE_EVENTS_HOST"] = host
+ keys.append(runner.get_cache_key())
+ self.assertEqual(len(set(keys)), 2 if native else 1)
+
+ @parameterized.expand(
+ [
+ (
+ workload,
+ None,
+ workload in (Workload.DEFAULT, Workload.ONLINE, Workload.OFFLINE, Workload.NEW_EVENTS_CLUSTER),
+ )
+ for workload in Workload
+ ]
+ + [(Workload.DEFAULT, Product.ENDPOINTS, False)]
+ )
+ def test_native_opt_in_accepts_only_analytics_workloads(
+ self, workload: Workload, product: Product | None, supported: bool
+ ) -> None:
+ executor = HogQLQueryExecutor(
+ query="SELECT 1",
+ team=self.team,
+ workload=workload,
+ modifiers=self.modifiers.model_copy(update={"useNewEventsCluster": True}),
+ )
+ executor.select_query = ast.SelectQuery(select=[ast.Constant(value=1)])
+ executor.clickhouse_sql = "SELECT 1"
+ executor.clickhouse_context = HogQLContext(team_id=self.team.pk, modifiers=executor.query_modifiers)
+ with (
+ tags_context(product=product),
+ patch.object(executor, "_detect_warehouse_sources"),
+ patch("posthog.hogql.query.sync_execute", return_value=([(1,)], [("1", "UInt8")])) as execute,
+ ):
+ if supported:
+ executor._execute_clickhouse_query()
+ self.assertEqual(execute.call_args.kwargs["workload"], Workload.NEW_EVENTS_CLUSTER)
+ else:
+ with self.assertRaisesRegex(ExposedHogQLError, "analytics workloads only"):
+ executor._execute_clickhouse_query()
+ execute.assert_not_called()
+
+
+@override_settings(CLICKHOUSE_NATIVE_EVENTS_HOST="native.example.com", CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA=False)
+class TestNewEventsClusterPilot(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.enterContext(override_instance_config("CLICKHOUSE_NATIVE_EVENTS_HOST", "native.example.com"))
+ self.enterContext(override_instance_config("CLICKHOUSE_NATIVE_EVENTS_TEAMS", [self.team.pk]))
+ self.enterContext(override_instance_config("CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA", False))
+
+ @parameterized.expand(
+ [
+ (modifiers, eligible, native_table, native_cluster)
+ for modifiers, eligible, native_table, native_cluster in (
+ ({"useNewEventsCluster": True}, True, True, True),
+ ({"useNewEventsCluster": True}, False, False, True),
+ ({}, True, False, False),
+ ({"useNewEventsSchema": True}, True, True, False),
+ ({"useNewEventsCluster": False, "useNewEventsSchema": True}, True, True, False),
+ )
+ ]
+ + [
+ (
+ {"useNewEventsCluster": True, modifier: True},
+ True,
+ True,
+ True,
+ sql,
+ )
+ for modifier, sql in (
+ ("usePreaggregatedTableTransforms", "SELECT count() FROM events WHERE event = '$pageview'"),
+ (
+ "usePreaggregatedIntermediateResults",
+ "SELECT toStartOfDay(timestamp), uniqExact(person_id) FROM events WHERE event = '$pageview' AND timestamp >= '2024-01-01' AND timestamp < '2024-01-08' GROUP BY toStartOfDay(timestamp)",
+ ),
+ )
+ ]
+ + [
+ ({"useNewEventsCluster": True}, True, True, True, "SELECT 1", "force_async"),
+ ({"useNewEventsCluster": True}, True, True, True, "SELECT 1", "force_blocking", True),
+ (
+ {"useNewEventsCluster": True},
+ True,
+ True,
+ True,
+ {"kind": "PropertyValuesQuery", "property_key": "$browser", "property_type": "event"},
+ ),
+ ]
+ )
+ def test_query_route_requires_an_eligible_explicit_blocking_opt_in(
+ self,
+ modifiers: dict[str, bool],
+ eligible: bool,
+ native_table: bool,
+ native_cluster: bool,
+ sql: str | dict[str, str] = "SELECT count() AS n FROM events",
+ refresh: str = "force_blocking",
+ async_: bool = False,
+ ) -> None:
+ query = {"kind": "HogQLQuery", "query": sql} if isinstance(sql, str) else sql
+ unsupported = native_cluster and (query["kind"] != "HogQLQuery" or refresh != "force_blocking" or async_)
+ with (
+ override_instance_config("CLICKHOUSE_NATIVE_EVENTS_TEAMS", [self.team.pk] if eligible else []),
+ patch(
+ "products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute",
+ return_value=0,
+ ) as insert,
+ patch("posthog.hogql.query.sync_execute", return_value=([(7,)], [("n", "UInt64")])) as execute,
+ patch("posthog.hogql_queries.query_runner.enqueue_process_query_task") as enqueue,
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/query/",
+ {
+ "query": {**query, "modifiers": modifiers},
+ "refresh": refresh,
+ "async": async_,
+ },
+ format="json",
+ )
+ rejected = native_cluster and (not eligible or unsupported)
+ self.assertEqual(response.status_code, 400 if rejected else 200, response.json())
+ enqueue.assert_not_called()
+ if rejected:
+ execute.assert_not_called()
+ if unsupported:
+ self.assertIn("Native cluster comparisons", response.json()["detail"])
+ return
+ self.assertEqual("events_json" in execute.call_args.args[0], native_table)
+ self.assertEqual(execute.call_args.kwargs["workload"] == Workload.NEW_EVENTS_CLUSTER, native_cluster)
+ if native_cluster:
+ insert.assert_not_called()
+ self.assertNotIn("pre_aggregated", execute.call_args.args[0])
+ self.assertNotIn("preaggregation_results", execute.call_args.args[0])
+ self.assertIs(response.json()["modifiers"]["useNewEventsCluster"], True)
diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.py
index 9dde15d47702..430e82f41092 100644
--- a/posthog/hogql_queries/hogql_query_runner.py
+++ b/posthog/hogql_queries/hogql_query_runner.py
@@ -68,6 +68,8 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
self._direct_engine: str | None = None
self._managed_warehouse_sql_mode: ManagedWarehouseSQLMode | None = None
super().__init__(*args, **kwargs)
+ if self.query.connectionId and self.modifiers.useNewEventsCluster:
+ raise ExposedHogQLError("Native events cluster queries cannot use a warehouse connection.")
# Treat SQL query caching like day insight
def cache_target_age(self, last_refresh: Optional[datetime], lazy: bool = False) -> Optional[datetime]:
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 765723bdd5c4..f3fc8bc7a58a 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -126,6 +126,7 @@ from posthog.hogql import ast
from posthog.hogql.constants import LimitContext
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
+from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.modifiers import create_default_modifiers_for_user
from posthog.hogql.printer import prepare_and_print_ast, to_printed_hogql
from posthog.hogql.query import create_default_modifiers_for_team
@@ -185,6 +186,7 @@ from posthog.hogql_queries.validation.validation import (
run_validation_rules,
)
from posthog.models import Team, User
+from posthog.models.event.new_events_schema import get_new_events_cluster_host, new_events_cluster_host_scope
from posthog.models.instance_setting import get_instance_setting
from posthog.models.team import WeekStartDay
from posthog.models.team.event_retention import events_retention_months_for_team
@@ -2317,6 +2319,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
query_duration_ms = round((perf_counter() - query_start_time) * 1000, 2)
return query_result, query_duration_ms
+ @new_events_cluster_host_scope()
def run(
self,
execution_mode: ExecutionMode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
@@ -2327,6 +2330,12 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
cache_age_seconds: Optional[int] = None,
analytics_props: Optional[AnalyticsProps] = None,
) -> CR | CacheMissResponse | QueryStatusResponse:
+ if self.modifiers.useNewEventsCluster:
+ if not isinstance(self.query, HogQLQuery):
+ raise ExposedHogQLError("Native cluster comparisons currently support HogQLQuery only.")
+ if execution_mode != ExecutionMode.CALCULATE_BLOCKING_ALWAYS:
+ raise ExposedHogQLError("Native cluster comparisons require refresh=force_blocking and async=false.")
+
# Set user for access control during query execution. Some subclasses
# (e.g. QueryRunnerWithHogQLContext) construct user-dependent state in
# __init__; let them refresh it now that we know the real user. Only on an
@@ -3091,7 +3100,6 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# note: to_dict already strips custom_name from series (see schema_helpers.py)
query = to_dict(self.query)
query.pop("tags", None)
-
payload = {
"query_runner": self.__class__.__name__,
"query": query,
@@ -3103,6 +3111,8 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
"week_start_day": self.team.week_start_day or WeekStartDay.SUNDAY,
"version": 2,
}
+ if self.modifiers.useNewEventsCluster:
+ payload["native_events_host"] = get_new_events_cluster_host()
# Include property-level access control restrictions in the cache key so that
# users with different property restrictions get separate cache entries.
diff --git a/posthog/models/event/new_events_schema.py b/posthog/models/event/new_events_schema.py
index 4624e20c656d..4400be21c41a 100644
--- a/posthog/models/event/new_events_schema.py
+++ b/posthog/models/event/new_events_schema.py
@@ -1,3 +1,6 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
+from contextvars import ContextVar
from typing import TYPE_CHECKING
from django.conf import settings
@@ -8,6 +11,47 @@ if TYPE_CHECKING:
from posthog.schema import HogQLQueryModifiers
+# TODO: Remove the per-query rollout option after the events cluster migration is complete.
+_query_host: ContextVar[list[str | None] | None] = ContextVar("new_events_cluster_host", default=None)
+
+
+def get_new_events_cluster_host() -> str | None:
+ snapshot = _query_host.get()
+ if snapshot:
+ return snapshot[0]
+ value = get_instance_setting("CLICKHOUSE_NATIVE_EVENTS_HOST")
+ host = value if isinstance(value, str) and value else None
+ if snapshot is not None:
+ snapshot.append(host)
+ return host
+
+
+@contextmanager
+def new_events_cluster_host_scope() -> Iterator[None]:
+ # Pin cache lookup and execution to one host even if settings change mid-request.
+ if _query_host.get() is not None:
+ yield
+ return
+ token = _query_host.set([])
+ try:
+ yield
+ finally:
+ _query_host.reset(token)
+
+
+def use_new_events_cluster(team_id: int | None, modifiers: "HogQLQueryModifiers | None") -> bool:
+ from posthog.hogql.errors import ExposedHogQLError # noqa: PLC0415
+
+ if modifiers is None or not modifiers.useNewEventsCluster:
+ return False
+ if not get_new_events_cluster_host():
+ raise ExposedHogQLError("The native events cluster host is not configured.")
+ allowed = get_instance_setting("CLICKHOUSE_NATIVE_EVENTS_TEAMS")
+ if not isinstance(allowed, list) or any(type(value) is not int for value in allowed) or team_id not in allowed:
+ raise ExposedHogQLError("This project is not enabled for native events cluster queries.")
+ return True
+
+
def use_new_events_schema(team_id: int | None = None, modifiers: "HogQLQueryModifiers | None" = None) -> bool:
"""Whether HogQL reads should target the native-JSON events tables.
diff --git a/posthog/schema.py b/posthog/schema.py
index f30ca3bc16c9..02c8a656e811 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -6315,6 +6315,17 @@ class HogQLQueryModifiers(BaseModel):
),
)
useMaterializedViews: bool | None = None
+ useNewEventsCluster: bool | None = Field(
+ default=None,
+ description=(
+ "Read this query from the native events cluster and native JSON events"
+ " table (`true`), or keep its existing connection (`false` or unset). This"
+ " is an internal rollout switch for eligible projects. PostHog staff manage"
+ " eligibility through instance settings. Each query must opt in; project"
+ " defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons"
+ " are supported."
+ ),
+ )
useNewEventsSchema: bool | None = Field(
default=None,
description=(
diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.py
index 459775c73caf..4cb7be6b9809 100644
--- a/posthog/settings/dynamic_settings.py
+++ b/posthog/settings/dynamic_settings.py
@@ -72,6 +72,16 @@ CONSTANCE_CONFIG = {
"Comma-separated team IDs whose HogQL queries read from the native-JSON events tables even while the global setting is off.",
str,
),
+ "CLICKHOUSE_NATIVE_EVENTS_HOST": (
+ get_from_env("CLICKHOUSE_NATIVE_EVENTS_HOST", ""),
+ "Hostname for explicit new events cluster queries, without a scheme, port or path. Empty disables the route. Changes reach workers within about a minute.",
+ str,
+ ),
+ "CLICKHOUSE_NATIVE_EVENTS_TEAMS": (
+ [],
+ "Project IDs eligible for explicit native events cluster query opt-ins. This does not change query defaults.",
+ list[int],
+ ),
"PERSON_ON_EVENTS_V2_ENABLED": (
# Person-on-events v2 reads are the production default for every project created
# since 2024-06-14, and both CI lanes set this variable so their runs match it. A
@@ -446,6 +456,8 @@ SETTINGS_ALLOWING_API_OVERRIDE = (
"PERSON_ON_EVENTS_V2_ENABLED",
"CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA",
"CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA_TEAMS",
+ "CLICKHOUSE_NATIVE_EVENTS_HOST",
+ "CLICKHOUSE_NATIVE_EVENTS_TEAMS",
"STRICT_CACHING_TEAMS",
"GITHUB_APP_SLUG",
"SLACK_APP_CLIENT_ID",
diff --git a/products/batch_exports/backend/presentation/views/utils.py b/products/batch_exports/backend/presentation/views/utils.py
index 49189101ac0d..91dde38998ed 100644
--- a/products/batch_exports/backend/presentation/views/utils.py
+++ b/products/batch_exports/backend/presentation/views/utils.py
@@ -73,6 +73,10 @@ class HogQLModifiersField(serializers.JSONField):
messages.append(f"{location}: {error['msg']}" if location else error["msg"])
raise serializers.ValidationError(messages) from e
else:
+ if modifiers.useNewEventsCluster:
+ raise serializers.ValidationError(
+ "Native events cluster queries are only supported by the synchronous query API"
+ )
self.loaded = modifiers
return modifiers.model_dump(mode="json", exclude_none=True)
diff --git a/products/batch_exports/backend/tests/api/test_create.py b/products/batch_exports/backend/tests/api/test_create.py
index a66752584d7d..c6f2c4fda877 100644
--- a/products/batch_exports/backend/tests/api/test_create.py
+++ b/products/batch_exports/backend/tests/api/test_create.py
@@ -739,6 +739,11 @@ def test_create_batch_export_with_hogql_model_allows_query_without_placeholders(
"hogql_modifiers",
"notAModifier: Extra inputs are not permitted",
),
+ (
+ {"hogql_modifiers": {"useNewEventsCluster": True}},
+ "hogql_modifiers",
+ "Native events cluster queries are only supported by the synchronous query API",
+ ),
(
{"model": "events", "hogql_modifiers": {"convertToProjectTimezone": False}},
"hogql_modifiers",
@@ -752,6 +757,7 @@ def test_create_batch_export_with_hogql_model_allows_query_without_placeholders(
"unaliased-column",
"filters",
"unknown-modifier",
+ "native-cluster-modifier",
"modifiers-with-events-model",
],
)
@@ -776,6 +782,7 @@ def test_create_batch_export_with_hogql_model_fails_with_invalid_request(
# HogQL may append field name suggestions to a resolution error, so match on the prefix.
assert response.json()["detail"].startswith(expected_error_message), response.json()["detail"]
assert BatchExportSource.objects.for_team(team.pk).count() == 0
+ assert not BatchExport.objects.filter(team=team).exists()
def test_cannot_create_batch_export_with_hogql_model_if_not_enabled(
diff --git a/products/batch_exports/backend/tests/api/test_serializers.py b/products/batch_exports/backend/tests/api/test_serializers.py
index c2dc69bd110c..c1fd88dc686e 100644
--- a/products/batch_exports/backend/tests/api/test_serializers.py
+++ b/products/batch_exports/backend/tests/api/test_serializers.py
@@ -22,6 +22,7 @@ from products.batch_exports.backend.presentation.views.batch_export.exports impo
BatchExportSerializer,
parse_events_hogql_query,
)
+from products.batch_exports.backend.presentation.views.utils import HogQLModifiersField
class TestBatchExportModelValidation(SimpleTestCase):
@@ -48,6 +49,23 @@ class TestBatchExportModelValidation(SimpleTestCase):
assert serializer.is_valid(), serializer.errors
assert serializer.validated_data == {"name": "Renamed"}
+ @parameterized.expand(
+ [
+ ("unset", {}, {}),
+ ("false", {"useNewEventsCluster": False}, {"useNewEventsCluster": False}),
+ ("true", {"useNewEventsCluster": True}, None),
+ ]
+ )
+ def test_cluster_opt_ins_are_not_supported_by_exports(
+ self, _name: str, modifiers: dict, expected: dict | None
+ ) -> None:
+ field = HogQLModifiersField()
+ if expected is None:
+ with self.assertRaisesMessage(serializers.ValidationError, "synchronous query API"):
+ field.run_validation(modifiers)
+ else:
+ assert field.run_validation(modifiers) == expected
+
def prepare_query(query: str, team_id: int) -> ast.SelectQuery:
"""Parse and resolve a HogQL query string into a prepared AST."""
diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
index bb2a9a1d4097..4093c933dff2 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
@@ -826,6 +826,11 @@ class TestFileDownloadHogQL:
"'data_interval_start' and 'data_interval_end' are required",
id="events-model-missing-intervals",
),
+ pytest.param(
+ {"hogql_modifiers": {"useNewEventsCluster": True}},
+ "synchronous query API",
+ id="native-cluster-modifier",
+ ),
pytest.param(
{"model": "events", "hogql_query": None, "hogql_modifiers": {"convertToProjectTimezone": False}},
"'hogql_modifiers' are only supported when 'model' is 'hogql'",
@@ -1251,6 +1256,15 @@ class TestFileDownloadHogQL:
"Extra inputs are not permitted",
id="unknown-modifier",
),
+ pytest.param(
+ {
+ "model": "hogql",
+ "hogql_query": "SELECT event AS event FROM events",
+ "hogql_modifiers": {"useNewEventsCluster": True},
+ },
+ "synchronous query API",
+ id="native-cluster-modifier",
+ ),
],
)
@pytest.mark.usefixtures("enable_hogql_flag")
diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.ts
index ec6b1a2dea90..119da89c0f7b 100644
--- a/products/batch_exports/frontend/generated/api.schemas.ts
+++ b/products/batch_exports/frontend/generated/api.schemas.ts
@@ -859,6 +859,8 @@ export interface HogQLQueryModifiersApi {
/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
typeAwareCastSimplification?: boolean | null
useMaterializedViews?: boolean | null
+ /** Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported. */
+ useNewEventsCluster?: boolean | null
/** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */
useNewEventsSchema?: boolean | null
usePreaggregatedIntermediateResults?: boolean | null
diff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.ts
index 9be37aeec211..0a5482befcab 100644
--- a/products/batch_exports/frontend/generated/api.zod.ts
+++ b/products/batch_exports/frontend/generated/api.zod.ts
@@ -663,6 +663,12 @@ export const BatchExportsCreateBody = /* @__PURE__ */ zod
'Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types'
),
useMaterializedViews: zod.union([zod.boolean(), zod.null()]).optional(),
+ useNewEventsCluster: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported.'
+ ),
useNewEventsSchema: zod
.union([zod.boolean(), zod.null()])
.optional()
@@ -1620,6 +1626,12 @@ export const BatchExportsUpdateBody = /* @__PURE__ */ zod
'Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types'
),
useMaterializedViews: zod.union([zod.boolean(), zod.null()]).optional(),
+ useNewEventsCluster: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported.'
+ ),
useNewEventsSchema: zod
.union([zod.boolean(), zod.null()])
.optional()
@@ -2336,6 +2348,12 @@ export const BatchExportsPartialUpdateBody = /* @__PURE__ */ zod
'Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types'
),
useMaterializedViews: zod.union([zod.boolean(), zod.null()]).optional(),
+ useNewEventsCluster: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported.'
+ ),
useNewEventsSchema: zod
.union([zod.boolean(), zod.null()])
.optional()
@@ -3037,6 +3055,12 @@ export const BatchExportsRunTestStepCreateBody = /* @__PURE__ */ zod
'Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types'
),
useMaterializedViews: zod.union([zod.boolean(), zod.null()]).optional(),
+ useNewEventsCluster: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported.'
+ ),
useNewEventsSchema: zod
.union([zod.boolean(), zod.null()])
.optional()
@@ -3757,6 +3781,12 @@ export const BatchExportsRunTestStepNewCreateBody = /* @__PURE__ */ zod
'Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types'
),
useMaterializedViews: zod.union([zod.boolean(), zod.null()]).optional(),
+ useNewEventsCluster: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported.'
+ ),
useNewEventsSchema: zod
.union([zod.boolean(), zod.null()])
.optional()
@@ -4194,6 +4224,12 @@ export const FileDownloadBatchExportsCreateBody = /* @__PURE__ */ zod.union([
'Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types'
),
useMaterializedViews: zod.union([zod.boolean(), zod.null()]).optional(),
+ useNewEventsCluster: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported.'
+ ),
useNewEventsSchema: zod
.union([zod.boolean(), zod.null()])
.optional()
@@ -4452,6 +4488,12 @@ export const FileDownloadBatchExportsCountRowsCreateBody = /* @__PURE__ */ zod
'Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types'
),
useMaterializedViews: zod.union([zod.boolean(), zod.null()]).optional(),
+ useNewEventsCluster: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported.'
+ ),
useNewEventsSchema: zod
.union([zod.boolean(), zod.null()])
.optional()
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 4a62b65584ae..6bd5a71cc443 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -1789,6 +1789,8 @@ export interface HogQLQueryModifiersApi {
/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
typeAwareCastSimplification?: boolean | null
useMaterializedViews?: boolean | null
+ /** Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported. */
+ useNewEventsCluster?: boolean | null
/** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */
useNewEventsSchema?: boolean | null
usePreaggregatedIntermediateResults?: boolean | null
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 027753fc68b5..675abd2fb4ea 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1809,6 +1809,8 @@ export interface HogQLQueryModifiersApi {
/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
typeAwareCastSimplification?: boolean | null
useMaterializedViews?: boolean | null
+ /** Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported. */
+ useNewEventsCluster?: boolean | null
/** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */
useNewEventsSchema?: boolean | null
usePreaggregatedIntermediateResults?: boolean | null
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 0857fdbb05be..139ea90d9d28 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -228,6 +228,7 @@ export namespace Schemas {
timings: boolean | null;
typeAwareCastSimplification: boolean | null;
useMaterializedViews: boolean | null;
+ useNewEventsCluster: boolean | null;
useNewEventsSchema: boolean | null;
usePreaggregatedIntermediateResults: boolean | null;
usePreaggregatedTableTransforms: boolean | null;
diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.py
index af7e5c9dcbd8..f5614d29a00f 100644
--- a/products/endpoints/backend/logic/execution.py
+++ b/products/endpoints/backend/logic/execution.py
@@ -77,6 +77,7 @@ from products.endpoints.backend.insight_transformers import MaterializedSeriesMi
from products.endpoints.backend.logic.materialized_serving import serving_state_for_version
from products.endpoints.backend.logic.pagination import EndpointPagination
from products.endpoints.backend.logic.strategies import EndpointQueryStrategy, strategy_for
+from products.endpoints.backend.logic.validation import NATIVE_CLUSTER_UNSUPPORTED
from products.endpoints.backend.logs import build_execution_message, log_endpoint_execution
from products.endpoints.backend.metrics import (
ENDPOINT_CACHE_RESULT_TOTAL,
@@ -364,6 +365,8 @@ class EndpointExecutionService(PydanticModelMixin):
version: EndpointVersion,
offset: int | None = None,
) -> None:
+ if (version.query.get("modifiers") or {}).get("useNewEventsCluster"):
+ raise ValidationError({"query": NATIVE_CLUSTER_UNSUPPORTED})
strategy = strategy_for(endpoint, version, self.team)
is_materialized = bool(version.is_materialized and version.saved_query)
diff --git a/products/endpoints/backend/logic/validation.py b/products/endpoints/backend/logic/validation.py
index c2e73a77c84e..45bc5da80353 100644
--- a/products/endpoints/backend/logic/validation.py
+++ b/products/endpoints/backend/logic/validation.py
@@ -69,6 +69,9 @@ DIRECT_CONNECTION_UNSUPPORTED = (
"Endpoints can't query a direct connection. "
"Switch the connection to PostHog (ClickHouse) and query a synced table instead."
)
+NATIVE_CLUSTER_UNSUPPORTED = (
+ "Endpoints do not support native events cluster opt-ins. Use the query API for comparisons."
+)
def validate_hogql_query(query: HogQLQuery, team: Team, user: User) -> None:
@@ -278,6 +281,9 @@ def validate_optional_breakdown_properties(
def validate_endpoint_request(data: EndpointRequest, team: Team, user: User, strict: bool = True) -> None:
"""Validate a create/update payload. With strict=True, name and query are required."""
query = data.query
+ modifiers = getattr(query, "modifiers", None)
+ if modifiers and modifiers.useNewEventsCluster:
+ raise ValidationError({"query": NATIVE_CLUSTER_UNSUPPORTED})
if not query and strict:
raise ValidationError({"query": "This field is required."})
@@ -310,6 +316,9 @@ def validate_update_request(
version_number: int | None = None,
) -> None:
"""Validate an update payload against the endpoint's resulting state."""
+ modifiers = getattr(data.query, "modifiers", None)
+ if modifiers and modifiers.useNewEventsCluster:
+ raise ValidationError({"query": NATIVE_CLUSTER_UNSUPPORTED})
validate_data_freshness(data.data_freshness_seconds)
# Determine final states after this request (for validation)
diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.py
index 4dbfffa21865..628f2e15dd5b 100644
--- a/products/endpoints/backend/tests/test_endpoint.py
+++ b/products/endpoints/backend/tests/test_endpoint.py
@@ -48,7 +48,7 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):
secure_value=hash_key_value(self.api_key),
scopes=["*"],
)
- self.sample_hogql_query = {
+ self.sample_hogql_query: dict[str, Any] = {
"connectionId": None,
"executionTarget": None,
"explain": None,
@@ -69,15 +69,22 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):
"series": [{"kind": "EventsNode"}],
}
- def test_create_hogql_endpoint(self):
- """Test creating a endpoint successfully."""
+ @parameterized.expand([(None,), (True,)])
+ def test_create_hogql_endpoint(self, native: bool | None):
data = {
"name": "test_query",
"description": "Test query description",
"query": self.sample_hogql_query,
}
+ if native is not None:
+ data["query"] = {**self.sample_hogql_query, "modifiers": {"useNewEventsCluster": native}}
response = self.client.post(f"/api/environments/{self.team.id}/endpoints/", data, format="json")
+ if native:
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.json())
+ self.assertIn("not support native events cluster", str(response.json()))
+ self.assertFalse(Endpoint.objects.filter(team=self.team, name="test_query").exists())
+ return
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
response_data = response.json()
@@ -320,8 +327,8 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
- def test_update_endpoint(self):
- """Test updating an existing endpoint."""
+ @parameterized.expand([(None,), (True,)])
+ def test_update_endpoint(self, native: bool | None):
endpoint = create_endpoint_with_version(
name="update_test",
team=self.team,
@@ -330,16 +337,26 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):
created_by=self.user,
)
- updated_data = {
+ updated_query: dict[str, Any] = {"kind": "HogQLQuery", "query": "SELECT 1"}
+ if native is not None:
+ updated_query["modifiers"] = {"useNewEventsCluster": native}
+
+ updated_data: dict[str, Any] = {
"description": "Updated description",
"is_active": False,
- "query": {"kind": "HogQLQuery", "query": "SELECT 1"},
+ "query": updated_query,
}
response = self.client.put(
f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/", updated_data, format="json"
)
+ if native:
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.json())
+ self.assertIn("not support native events cluster", str(response.json()))
+ self.assertEqual(endpoint.versions.count(), 1)
+ return
+
response_data = response.json()
self.assertEqual(status.HTTP_200_OK, response.status_code, response_data)
diff --git a/products/endpoints/backend/tests/test_endpoint_query_tagging.py b/products/endpoints/backend/tests/test_endpoint_query_tagging.py
index 893d8392f3c8..0a7218d35017 100644
--- a/products/endpoints/backend/tests/test_endpoint_query_tagging.py
+++ b/products/endpoints/backend/tests/test_endpoint_query_tagging.py
@@ -1,9 +1,11 @@
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest import mock
+from parameterized import parameterized
from rest_framework import status
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.models.instance_setting import override_instance_config
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
@@ -42,9 +44,33 @@ class TestEndpointQueryTagging(ClickhouseTestMixin, APIBaseTest):
scopes=["*"],
)
- def test_run_via_session_auth_tags_endpoint_playground(self):
- with mock.patch("products.endpoints.backend.logic.execution.tag_queries", wraps=tag_queries) as spy:
+ @parameterized.expand([(None, False), (True, False), (True, True)])
+ def test_run_via_session_auth_tags_endpoint_playground(self, native: bool | None, warm_cache: bool):
+ version = self.endpoint.get_version()
+ assert version is not None
+ if native is not None:
+ version.query["modifiers"] = {"useNewEventsCluster": native}
+ version.save()
+ with (
+ override_instance_config("CLICKHOUSE_NATIVE_EVENTS_HOST", "native.example.com"),
+ override_instance_config("CLICKHOUSE_NATIVE_EVENTS_TEAMS", [self.team.pk]),
+ mock.patch("posthog.hogql.query.sync_execute", return_value=([(1,)], [("1", "UInt8")])) as execute,
+ mock.patch("products.endpoints.backend.logic.execution.tag_queries", wraps=tag_queries) as spy,
+ ):
+ if warm_cache:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/query/",
+ {"query": version.query, "refresh": "force_blocking", "async": False},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ execute.reset_mock()
response = self.client.post(self.run_url, {}, format="json")
+ if native:
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert "not support native events cluster" in str(response.json())
+ execute.assert_not_called()
+ return
assert response.status_code == status.HTTP_200_OK, response.json()
call = _find_endpoint_feature_call(spy)
assert call is not None, f"no tag_queries(product=ENDPOINTS, feature=...) call found: {spy.call_args_list}"
diff --git a/products/marketing_analytics/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.ts
index ec5e671422b7..8e9311e5ec6d 100644
--- a/products/marketing_analytics/frontend/generated/api.schemas.ts
+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts
@@ -1646,6 +1646,8 @@ export interface HogQLQueryModifiersApi {
/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
typeAwareCastSimplification?: boolean | null
useMaterializedViews?: boolean | null
+ /** Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported. */
+ useNewEventsCluster?: boolean | null
/** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */
useNewEventsSchema?: boolean | null
usePreaggregatedIntermediateResults?: boolean | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 9bb5a2fead29..c882279d98ee 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -673,6 +673,8 @@ export interface HogQLQueryModifiersApi {
/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
typeAwareCastSimplification?: boolean | null
useMaterializedViews?: boolean | null
+ /** Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported. */
+ useNewEventsCluster?: boolean | null
/** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */
useNewEventsSchema?: boolean | null
usePreaggregatedIntermediateResults?: boolean | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 45c9ccfb7a46..a3a14d3db306 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2689,6 +2689,8 @@ export namespace Schemas {
/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
typeAwareCastSimplification?: boolean | null;
useMaterializedViews?: boolean | null;
+ /** Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported. */
+ useNewEventsCluster?: boolean | null;
/** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */
useNewEventsSchema?: boolean | null;
usePreaggregatedIntermediateResults?: boolean | null;
diff --git a/services/mcp/src/generated/batch_exports/api.ts b/services/mcp/src/generated/batch_exports/api.ts
index 62c7fd42d075..45525ea9de04 100644
--- a/services/mcp/src/generated/batch_exports/api.ts
+++ b/services/mcp/src/generated/batch_exports/api.ts
@@ -675,6 +675,12 @@ export const BatchExportsCreateBody = () => zod
'Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types'
),
useMaterializedViews: zod.union([zod.boolean(), zod.null()]).optional(),
+ useNewEventsCluster: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported.'
+ ),
useNewEventsSchema: zod
.union([zod.boolean(), zod.null()])
.optional()
@@ -1395,6 +1401,12 @@ export const BatchExportsPartialUpdateBody = () => zod
'Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types'
),
useMaterializedViews: zod.union([zod.boolean(), zod.null()]).optional(),
+ useNewEventsCluster: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported.'
+ ),
useNewEventsSchema: zod
.union([zod.boolean(), zod.null()])
.optional()
@@ -1846,6 +1858,12 @@ export const FileDownloadBatchExportsCreateBody = () => zod.union([
'Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types'
),
useMaterializedViews: zod.union([zod.boolean(), zod.null()]).optional(),
+ useNewEventsCluster: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported.'
+ ),
useNewEventsSchema: zod
.union([zod.boolean(), zod.null()])
.optional()
@@ -2140,6 +2158,12 @@ export const FileDownloadBatchExportsCountRowsCreateBody = () => zod
'Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types'
),
useMaterializedViews: zod.union([zod.boolean(), zod.null()]).optional(),
+ useNewEventsCluster: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported.'
+ ),
useNewEventsSchema: zod
.union([zod.boolean(), zod.null()])
.optional()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json
index 59745f683118..f563bad29615 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json
@@ -1065,6 +1065,17 @@
}
]
},
+ "useNewEventsCluster": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported."
+ },
"useNewEventsSchema": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json
index aa1aaa708123..398b7864e56a 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json
@@ -1064,6 +1064,17 @@
}
]
},
+ "useNewEventsCluster": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported."
+ },
"useNewEventsSchema": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json
index 3993bea06e8b..59565947db9a 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json
@@ -540,6 +540,17 @@
}
]
},
+ "useNewEventsCluster": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported."
+ },
"useNewEventsSchema": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json
index bb77a6512c59..848e81446813 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json
@@ -769,6 +769,17 @@
}
]
},
+ "useNewEventsCluster": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported."
+ },
"useNewEventsSchema": {
"anyOf": [
{