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.

refactor(events-api): serve list/retrieve via EventsQueryRunner (#65307)

Sandy Spicerdc2f514e2fb6
diff --git a/posthog/api/event.py b/posthog/api/event.py
index e5ff36601b75..b6d7ac3ec158 100644
--- a/posthog/api/event.py
+++ b/posthog/api/event.py
@@ -9,7 +9,6 @@ from datetime import datetime
from typing import Any, Iterator, List, Optional, Union, cast # noqa: UP035
from django.conf import settings
-from django.core.cache import cache
from django.utils import timezone
from drf_spectacular.types import OpenApiTypes
@@ -35,14 +34,11 @@ from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATION
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.auth import PersonalAPIKeyAuthentication
-from posthog.clickhouse.client import query_with_columns
-from posthog.clickhouse.client.limit import get_events_list_rate_limiter
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.event_usage import get_request_analytics_properties
from posthog.exceptions_capture import capture_exception
-from posthog.models import Element, Filter, Person, PropertyDefinition, User
-from posthog.models.event.query_event_list import query_events_list
-from posthog.models.event.sql import SELECT_ONE_EVENT_SQL
+from posthog.models import Element, Person, PropertyDefinition, User
+from posthog.models.event.legacy_events_query import LegacyEventsListQuery, get_one_event
from posthog.models.event.util import ClickhouseEventSerializer
from posthog.models.person.util import get_persons_mapped_by_distinct_id
from posthog.models.team import Team
@@ -55,13 +51,7 @@ from posthog.rate_limit import (
EventValuesSustainedThrottle,
)
from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP
-from posthog.utils import (
- convert_property_value,
- flatten,
- generate_short_id,
- refresh_requested_by_client,
- relative_date_parse,
-)
+from posthog.utils import convert_property_value, flatten, refresh_requested_by_client, relative_date_parse
tracer = trace.get_tracer(__name__)
@@ -74,46 +64,40 @@ EVENT_VALUES_COUNTER = Counter(
QUERY_DEFAULT_EXPORT_LIMIT = 1_000
EVENT_LIST_MAX_LIMIT = 1_000
-# Progressive time windows in seconds: 1min, 5min, 15min, 1hr, 6hr, 24hr
-EVENT_LIST_TIME_WINDOWS = [60, 300, 900, 3600, 21600, 86400]
-EVENT_LIST_CACHE_TTL = 86400 # 24 hours
-EVENT_LIST_CACHE_KEY_PREFIX = "event_list_good_period"
+# Legacy property-filter keys the frontend still appends but EventsQuery's schema forbids.
+# They are render hints with no filter semantics, so dropping them preserves old behavior. Any
+# OTHER unexpected key is left in place so the schema rejects it (fail loud) rather than being
+# silently ignored.
+_LEGACY_PROPERTY_KEYS_TO_DROP = {"property_type", "property_type_format"}
-def _get_limit_size_category(limit: int) -> str:
- """Groups limits into size categories to limit cache key cardinality."""
- if limit < 1000:
- return "s"
- elif limit < 10000:
- return "m"
- return "l"
+def _clean_property_node(node: dict) -> dict:
+ """Drop legacy render-hint keys from a property filter, recursing into property groups.
-def _get_event_list_cache_key(
- team_id: int,
- has_event_filter: bool,
- has_distinct_id: bool,
- limit: int,
-) -> str:
- """
- Generate a cache key for the event list progressive window optimization.
-
- The cache stores {"window": int, "result_count": int} to track which time
- window worked and how many results it returned. When reading from cache,
- we only use the cached window if its result_count >= half_limit for the
- current request. This prevents the bug where a cached window that succeeded
- for a smaller limit (e.g., 4999 with half_limit=2499) is incorrectly used
- for a larger limit (e.g., 6000 with half_limit=3000) that needs more results.
-
- We use size categories (s/m/l) instead of exact limits to bound cache key
- cardinality to ~3 keys per team/filter combination. Within a size category,
- different limits share the same cache key but have different half_limit
- thresholds - the result_count validation handles this.
+ A group node (`{"type": "AND"/"OR", "values": [...]}`) keeps its structure so the runner's
+ `property_to_expr` preserves nested AND/OR; only leaf filters are key-filtered.
"""
- event_flag = "1" if has_event_filter else "0"
- distinct_id_flag = "1" if has_distinct_id else "0"
- size_category = _get_limit_size_category(limit)
- return f"{EVENT_LIST_CACHE_KEY_PREFIX}:{team_id}:{event_flag}:{distinct_id_flag}:{size_category}"
+ values = node.get("values")
+ if isinstance(values, list):
+ return {"type": node.get("type"), "values": [_clean_property_node(v) for v in values if isinstance(v, dict)]}
+ return {k: v for k, v in node.items() if k not in _LEGACY_PROPERTY_KEYS_TO_DROP}
+
+
+def _iter_leaf_property_filters(properties: "builtins.list[dict] | dict | None") -> Iterator[dict]:
+ """Yield the leaf filter dicts in a flat list or a (possibly nested) property group."""
+ stack: builtins.list[dict] = []
+ if isinstance(properties, dict):
+ stack.append(properties)
+ elif properties:
+ stack.extend(p for p in properties if isinstance(p, dict))
+ while stack:
+ node = stack.pop()
+ values = node.get("values")
+ if isinstance(values, list):
+ stack.extend(v for v in values if isinstance(v, dict))
+ else:
+ yield node
@dataclasses.dataclass(frozen=True)
@@ -298,115 +282,42 @@ class EventViewSet(
if offset > 50000 and (deprecate_offset or random.random() < 0.01): # 1% of queries fail
raise serializers.ValidationError("Offset is deprecated. Max supported offset value is 50000")
- filter = Filter(request=request, team=team)
+ properties = self._parse_properties_param(request)
order_by: list[str] = (
list(json.loads(request.GET["orderBy"])) if request.GET.get("orderBy") else ["-timestamp"]
)
+ order = "DESC" if len(order_by) == 1 and order_by[0] == "-timestamp" else "ASC"
restricted_context = self._get_restricted_properties_context(request, team)
- self._reject_restricted_property_references(filter, order_by, restricted_context)
-
- # Progressive time window optimization
- # Start with cached good_period or smallest window
- has_event_filter = bool(request.GET.get("event"))
- has_distinct_id = bool(request.GET.get("distinct_id"))
- cache_key = _get_event_list_cache_key(team.pk, has_event_filter, has_distinct_id, limit)
- cached_data = cache.get(cache_key)
-
- # Calculate the user's requested time range in seconds
- request_window_seconds: Optional[int] = None
- if request.GET.get("before") and request.GET.get("after"):
- try:
- before = relative_date_parse(request.GET["before"], team.timezone_info)
- after = relative_date_parse(request.GET["after"], team.timezone_info)
- request_window_seconds = int((before - after).total_seconds())
- except (ValueError, TypeError):
- pass
-
- # Build list of windows to try, only those shorter than request window
- windows_to_try = [
- w for w in EVENT_LIST_TIME_WINDOWS if request_window_seconds is None or w < request_window_seconds
- ]
-
- half_limit = max(limit // 2, 1) # At least 1 result required
-
- # Only use cached window if it returned enough results for our threshold.
- # This prevents the bug where a cached window that succeeded for a smaller
- # limit (e.g., 4999 with half_limit=2499) is used for a larger limit
- # (e.g., 6000 with half_limit=3000) that needs more results.
- cached_window = None
- if cached_data and isinstance(cached_data, dict):
- cached_result_count = cached_data.get("result_count", 0)
- if cached_result_count >= half_limit:
- cached_window = cached_data.get("window")
- elif cached_data and isinstance(cached_data, int):
- # Backwards compatibility: old cache format was just the window integer
- cached_window = cached_data
-
- if cached_window and cached_window in windows_to_try:
- windows_to_try.remove(cached_window)
- windows_to_try.insert(0, cached_window)
-
- task_id = generate_short_id()
-
- with get_events_list_rate_limiter().run(team_id=team.pk, task_id=task_id):
- query_result: list = []
- successful_window: Optional[int] = None
- applied_window: Optional[int] = None
-
- for window in windows_to_try:
- query_result, applied_window = query_events_list(
- filter=filter,
- team=team,
- limit=limit,
- offset=offset,
- request_get_query_dict=request.GET.dict(),
- order_by=order_by,
- action_id=request.GET.get("action_id"),
- time_window_seconds=window,
- )
-
- # If window wasn't applied (e.g., ASC order), don't try other windows
- if applied_window is None:
- break
-
- if len(query_result) >= half_limit:
- successful_window = window
- break
-
- if successful_window:
- # Cache the successful window AND result count for future requests.
- # This allows requests with smaller limits to reuse cached windows,
- # while requests with larger limits will find their own windows.
- # Cache format: {"window": int, "result_count": int} (or int for legacy)
- new_cache_data = {"window": successful_window, "result_count": len(query_result)}
- if new_cache_data != cached_data:
- cache.set(cache_key, new_cache_data, EVENT_LIST_CACHE_TTL)
- elif applied_window is not None or not windows_to_try:
- # Windows were applied but didn't return enough results, or no windows to try - run full query
- query_result, _ = query_events_list(
- filter=filter,
- team=team,
- limit=limit,
- offset=offset,
- request_get_query_dict=request.GET.dict(),
- order_by=order_by,
- action_id=request.GET.get("action_id"),
- )
+ self._reject_restricted_property_references(properties, order_by, restricted_context)
+
+ request_user = cast(Optional[User], request.user if request.user.is_authenticated else None)
+ query_result, has_more = LegacyEventsListQuery(team, request_user).run(
+ limit=limit,
+ offset=offset,
+ order=order,
+ before=request.GET.get("before"),
+ after=request.GET.get("after"),
+ event=request.GET.get("event"),
+ person_id=request.GET.get("person_id"),
+ distinct_id=request.GET.get("distinct_id"),
+ properties=properties,
+ action_id=request.GET.get("action_id"),
+ )
context = {**restricted_context}
if request.query_params.get("include_person", "").lower() in ("true", "1"):
context["people"] = self._get_people(query_result, team)
result = ClickhouseEventSerializer(
- query_result[0:limit],
+ query_result,
many=True,
context=context,
).data
next_url: Optional[str] = None
- if not is_csv_request and len(query_result) > limit:
- next_url = self._build_next_url(request, query_result[limit - 1]["timestamp"], order_by)
+ if not is_csv_request and has_more and query_result:
+ next_url = self._build_next_url(request, query_result[-1]["timestamp"], order_by)
headers = None
if settings.PATCH_EVENT_LIST_MAX_OFFSET > 0:
headers = {"X-PostHog-Warn": "https://posthog.com/docs/api/events"}
@@ -456,14 +367,11 @@ class EventViewSet(
status=400,
)
tag_queries(product=ProductKey.PRODUCT_ANALYTICS, feature=Feature.QUERY)
- query_result = query_with_columns(
- SELECT_ONE_EVENT_SQL,
- {"team_id": self.team.pk, "event_id": pk.replace("-", "")},
- team_id=self.team.pk,
- )
- if len(query_result) == 0:
+ event = get_one_event(self.team, pk)
+ if event is None:
raise NotFound(detail=f"No events exist for event UUID {pk}")
+ query_result = [event]
query_context = {**self._get_restricted_properties_context(request, self.team)}
if request.query_params.get("include_person", "").lower() in ("true", "1"):
query_context["people"] = self._get_people(query_result, self.team)
@@ -682,9 +590,30 @@ class EventViewSet(
resp["Cache-Control"] = "max-age=10"
return resp
+ def _parse_properties_param(self, request: request.Request) -> "builtins.list[dict] | dict | None":
+ """Parse the `properties` query param for `EventsQuery`.
+
+ A flat list of leaf filters maps to `EventsQuery.properties`; a property group
+ (`{"type": "AND"/"OR", "values": [...]}`, possibly nested) is returned intact and later
+ forwarded to the runner's `property_to_expr` via `fixedProperties`, so its AND/OR survives.
+ Legacy-only keys (`property_type`, `property_type_format`) the schema rejects are dropped;
+ missing `type` defaults to `event` as before. Invalid JSON raises the legacy 400."""
+ raw = request.GET.get("properties")
+ if not raw:
+ return None
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError:
+ raise serializers.ValidationError("Properties are unparsable!")
+ if isinstance(parsed, dict) and isinstance(parsed.get("values"), list):
+ return _clean_property_node(parsed)
+ if isinstance(parsed, list):
+ return [_clean_property_node(prop) for prop in parsed if isinstance(prop, dict)]
+ return None
+
def _reject_restricted_property_references(
self,
- filter: Filter,
+ properties: "builtins.list[dict] | dict | None",
order_by: builtins.list[str],
restricted_context: dict,
) -> None:
@@ -696,10 +625,12 @@ class EventViewSet(
if not restricted_event and not restricted_person:
return
- for prop in filter.property_groups.flat:
- if prop.type == "event" and prop.key in restricted_event:
+ for prop in _iter_leaf_property_filters(properties):
+ prop_type = prop.get("type", "event")
+ key = prop.get("key")
+ if prop_type == "event" and key in restricted_event:
raise serializers.ValidationError("Filter references a restricted property")
- if prop.type == "person" and prop.key in restricted_person:
+ if prop_type == "person" and key in restricted_person:
raise serializers.ValidationError("Filter references a restricted property")
for entry in order_by:
diff --git a/posthog/api/test/test_event.py b/posthog/api/test/test_event.py
index 9cd0635f047f..0c303dee1585 100644
--- a/posthog/api/test/test_event.py
+++ b/posthog/api/test/test_event.py
@@ -24,7 +24,7 @@ from parameterized import parameterized
from rest_framework import status
from posthog.models import Element, Organization, PropertyDefinition, User
-from posthog.models.event.query_event_list import insight_query_with_columns
+from posthog.models.event.legacy_events_query import _execute_events_list_query
from posthog.test.persons import create_person
from posthog.test.test_journeys import journeys_for
@@ -101,9 +101,11 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- # Django session, PostHog user, PostHog team, PostHog org membership,
- # instance setting check
- with self.assertNumQueries(9):
+ # Auth/team/membership/instance-setting lookups, plus the HogQL pipeline's per-probe
+ # access-control checks (the progressive-window loop probes several windows on this
+ # sparse dataset; the schema is built once and shared). Group-type-mapping is read via
+ # personhog, not Postgres, so it's not in this count.
+ with self.assertNumQueries(16):
response = self.client.get(f"/api/projects/{self.team.id}/events/?event=event_name").json()
assert response["results"][0]["event"] == "event_name"
@@ -128,9 +130,11 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- # Django session, PostHog user, PostHog team, PostHog org membership,
- # access control, instance settings (poe, rate limit)
- expected_queries = 10
+ # Auth/team/membership/access-control/instance-setting lookups, plus the HogQL
+ # pipeline's per-probe access-control checks. The progressive-window loop probes several
+ # windows on this sparse dataset; the HogQL schema is built once and shared across them.
+ # Group-type-mapping is read via personhog, not Postgres, so it's not in this count.
+ expected_queries = 24
with self.assertNumQueries(expected_queries):
response = self.client.get(
@@ -146,6 +150,32 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json() == self.validation_error_response("Properties are unparsable!", "invalid_input")
+ def test_filter_events_by_nested_property_group(self):
+ # A property group with an inner OR must keep OR semantics, not collapse to AND:
+ # (browser = Safari OR Chrome) AND os = Windows
+ _create_event(event="e", team=self.team, distinct_id="2", properties={"$browser": "Safari", "$os": "Windows"})
+ _create_event(event="e", team=self.team, distinct_id="2", properties={"$browser": "Chrome", "$os": "Windows"})
+ _create_event(event="e", team=self.team, distinct_id="2", properties={"$browser": "Firefox", "$os": "Windows"})
+ _create_event(event="e", team=self.team, distinct_id="2", properties={"$browser": "Safari", "$os": "Mac"})
+ flush_persons_and_events()
+
+ group = {
+ "type": "AND",
+ "values": [
+ {
+ "type": "OR",
+ "values": [
+ {"key": "$browser", "value": "Safari", "type": "event"},
+ {"key": "$browser", "value": "Chrome", "type": "event"},
+ ],
+ },
+ {"key": "$os", "value": "Windows", "type": "event"},
+ ],
+ }
+ response = self.client.get(f"/api/projects/{self.team.id}/events/?properties={json.dumps(group)}").json()
+ # Firefox/Windows fails the OR; Safari/Mac fails the os filter — both excluded.
+ assert sorted(r["properties"]["$browser"] for r in response["results"]) == ["Chrome", "Safari"]
+
def test_filter_events_by_precalculated_cohort(self):
create_person(team=self.team, distinct_ids=["p1"], properties={"key": "value"})
_create_event(
@@ -224,9 +254,21 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
assert len(response["results"]) == 2
def test_filter_by_nonexisting_person(self):
- response = self.client.get(f"/api/projects/{self.team.id}/events/?person_id=5555555555")
- assert response.status_code == 200
- assert len(response.json()["results"]) == 0
+ # Events exist for a real person; a person_id that resolves to nobody must return nothing —
+ # not fall through to all events. Guards the "no match -> empty" case for both id forms.
+ _create_person(distinct_ids=["real"], team=self.team, immediate=True)
+ _create_event(event="random event", team=self.team, distinct_id="real")
+ flush_persons_and_events()
+
+ nonexistent_pk = self.client.get(f"/api/projects/{self.team.id}/events/?person_id=5555555555")
+ assert nonexistent_pk.status_code == 200
+ assert len(nonexistent_pk.json()["results"]) == 0
+
+ nonexistent_uuid = self.client.get(
+ f"/api/projects/{self.team.id}/events/?person_id=550e8400-e29b-41d4-a716-446655440000"
+ )
+ assert nonexistent_uuid.status_code == 200
+ assert len(nonexistent_uuid.json()["results"]) == 0
@freeze_time("2020-01-10")
def test_event_column_values(self):
@@ -1005,48 +1047,54 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
response_invalid_token = self.client.get(f"/api/projects/{self.team.id}/events?token=invalid")
assert response_invalid_token.status_code == 401
- @patch("posthog.models.event.query_event_list.insight_query_with_columns")
- def test_optimize_query_progressive_windows(self, patch_query_with_columns):
+ @patch("posthog.models.event.legacy_events_query._execute_events_list_query")
+ def test_optimize_query_progressive_windows(self, patch_execute_query):
# Progressive time window optimization: tries increasingly larger windows
# until finding one with >= half_limit results, then falls back to full range
# Windows: [60, 300, 900, 3600, 21600, 86400] seconds
# With only 1 result (< half of default limit 100), tries all 6 windows + fallback = 7 calls
- patch_query_with_columns.return_value = [
- {
- "uuid": "event",
- "event": "d",
- "properties": "{}",
- "timestamp": timezone.now(),
- "team_id": "d",
- "distinct_id": "d",
- "elements_chain": "d",
- }
- ]
+ patch_execute_query.return_value = (
+ [
+ {
+ "uuid": "event",
+ "event": "d",
+ "properties": "{}",
+ "timestamp": timezone.now(),
+ "team_id": "d",
+ "distinct_id": "d",
+ "elements_chain": "d",
+ }
+ ],
+ False,
+ )
response = self.client.get(f"/api/projects/{self.team.id}/events/").json()
assert len(response["results"]) == 1
- assert patch_query_with_columns.call_count == 7 # 6 windows + 1 fallback
+ assert patch_execute_query.call_count == 7 # 6 windows + 1 fallback
# With 50+ results (>= half of limit 100), succeeds on first window = 1 call
- patch_query_with_columns.reset_mock()
- patch_query_with_columns.return_value = [
- {
- "uuid": "event",
- "event": "d",
- "properties": "{}",
- "timestamp": timezone.now(),
- "team_id": "d",
- "distinct_id": "d",
- "elements_chain": "d",
- }
- for _ in range(0, 50)
- ]
+ patch_execute_query.reset_mock()
+ patch_execute_query.return_value = (
+ [
+ {
+ "uuid": "event",
+ "event": "d",
+ "properties": "{}",
+ "timestamp": timezone.now(),
+ "team_id": "d",
+ "distinct_id": "d",
+ "elements_chain": "d",
+ }
+ for _ in range(0, 50)
+ ],
+ False,
+ )
response = self.client.get(f"/api/projects/{self.team.id}/events/").json()
- assert patch_query_with_columns.call_count == 1
+ assert patch_execute_query.call_count == 1
- @patch("posthog.models.event.query_event_list.insight_query_with_columns", wraps=insight_query_with_columns)
+ @patch("posthog.models.event.legacy_events_query._execute_events_list_query", wraps=_execute_events_list_query)
@override_settings(PATCH_EVENT_LIST_MAX_OFFSET=2)
- def test_default_after(self, patch_query_with_columns):
+ def test_default_after(self, patch_execute_query):
# With PATCH_EVENT_LIST_MAX_OFFSET=2, default after = before - 24h
# Progressive windows to try (< 86400s): [60, 300, 900, 3600, 21600] = 5 windows
# Events at: 01-01T01:01, 01-02T02:02, ..., 01-09T09:09
@@ -1065,25 +1113,25 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
# Tries all 5 windows + fallback = 6 calls
response = self.client.get(f"/api/projects/{self.team.id}/events/?before=2024-01-01T00:02:02Z").json()
assert len(response["results"]) == 0
- assert patch_query_with_columns.call_count == 6
+ assert patch_execute_query.call_count == 6
# Event at 01-05T05:05:00 found in 300s window (05:01:02 - 05:06:02)
# 60s fails, 300s succeeds = 2 calls (cumulative: 8)
response = self.client.get(f"/api/projects/{self.team.id}/events/?before=2024-01-05T05:06:02Z&limit=1").json()
assert len(response["results"]) == 1
- assert patch_query_with_columns.call_count == 8
+ assert patch_execute_query.call_count == 8
# Events end at 01-09T09:09, all windows too narrow, fallback succeeds
# 5 windows + fallback = 6 calls (cumulative: 14)
response = self.client.get(f"/api/projects/{self.team.id}/events/?before=2024-01-10T09:01:02Z&limit=1").json()
assert len(response["results"]) == 1
- assert patch_query_with_columns.call_count == 14
+ assert patch_execute_query.call_count == 14
# No events after 01-09T09:09, all windows fail including fallback
# 5 windows + fallback = 6 calls (cumulative: 20)
response = self.client.get(f"/api/projects/{self.team.id}/events/?before=2024-01-10T10:20:02Z&limit=1").json()
assert len(response["results"]) == 0
- assert patch_query_with_columns.call_count == 20
+ assert patch_execute_query.call_count == 20
def test_optimize_query_with_bounded_dates(self):
# Test that bounded date ranges return correct results
@@ -1247,9 +1295,62 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
assert [r["event"] for r in response["results"]] == ["should_be_included"]
+class TestEventListRestrictedProperties(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ from posthog.constants import AvailableFeature
+
+ from products.access_control.backend.models.property_access_control import PropertyAccessControl
+ from products.access_control.backend.property_access_control import PropertyAccessLevel
+
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ secret = PropertyDefinition.objects.create(
+ team=self.team, name="secret_prop", property_type="String", type=PropertyDefinition.Type.EVENT
+ )
+ # A default rule (no member/role) restricts the property for everyone, including admins.
+ PropertyAccessControl.objects.create(
+ team=self.team, property_definition=secret, access_level=PropertyAccessLevel.NONE.value
+ )
+
+ def test_filter_referencing_restricted_property_is_rejected(self):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/events/?properties={json.dumps([{'key': 'secret_prop', 'value': 'x', 'type': 'event'}])}"
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "restricted property" in response.json()["detail"]
+
+ def test_nested_group_referencing_restricted_property_is_rejected(self):
+ # The restricted key is buried inside a nested OR — the walk must still find it.
+ group = {
+ "type": "AND",
+ "values": [
+ {"type": "OR", "values": [{"key": "secret_prop", "value": "x", "type": "event"}]},
+ ],
+ }
+ response = self.client.get(f"/api/projects/{self.team.id}/events/?properties={json.dumps(group)}")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "restricted property" in response.json()["detail"]
+
+ def test_order_by_referencing_restricted_property_is_rejected(self):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/events/?orderBy={json.dumps(['properties.secret_prop'])}"
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "restricted property" in response.json()["detail"]
+
+ def test_unrestricted_property_filter_is_allowed(self):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/events/?properties={json.dumps([{'key': 'public_prop', 'value': 'x', 'type': 'event'}])}"
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+
class TestEventListTimeWindowOptimization(ClickhouseTestMixin, APIBaseTest):
def test_cache_key_generation(self):
- from posthog.api.event import _get_event_list_cache_key, _get_limit_size_category
+ from posthog.models.event.legacy_events_query import _get_event_list_cache_key, _get_limit_size_category
# Test limit size categories
assert _get_limit_size_category(100) == "s"
@@ -1267,24 +1368,27 @@ class TestEventListTimeWindowOptimization(ClickhouseTestMixin, APIBaseTest):
assert _get_event_list_cache_key(123, True, True, 5000) == "event_list_good_period:123:1:1:m"
assert _get_event_list_cache_key(123, True, True, 15000) == "event_list_good_period:123:1:1:l"
- @patch("posthog.api.event.cache")
- @patch("posthog.models.event.query_event_list.insight_query_with_columns")
- def test_caches_successful_window_with_result_count(self, patch_query_with_columns, mock_cache):
+ @patch("posthog.models.event.legacy_events_query.cache")
+ @patch("posthog.models.event.legacy_events_query._execute_events_list_query")
+ def test_caches_successful_window_with_result_count(self, patch_execute_query, mock_cache):
mock_cache.get.return_value = None # No cached window
# Return enough results (>= half of limit) to succeed on first window
- patch_query_with_columns.return_value = [
- {
- "uuid": "event",
- "event": "test",
- "properties": "{}",
- "timestamp": timezone.now(),
- "team_id": str(self.team.pk),
- "distinct_id": "1",
- "elements_chain": "",
- }
- for _ in range(50)
- ]
+ patch_execute_query.return_value = (
+ [
+ {
+ "uuid": "event",
+ "event": "test",
+ "properties": "{}",
+ "timestamp": timezone.now(),
+ "team_id": str(self.team.pk),
+ "distinct_id": "1",
+ "elements_chain": "",
+ }
+ for _ in range(50)
+ ],
+ False,
+ )
self.client.get(f"/api/projects/{self.team.id}/events/")
@@ -1295,37 +1399,40 @@ class TestEventListTimeWindowOptimization(ClickhouseTestMixin, APIBaseTest):
assert cached_data == {"window": 60, "result_count": 50}
assert call_args[0][2] == 86400 # TTL
- @patch("posthog.api.event.cache")
- @patch("posthog.models.event.query_event_list.insight_query_with_columns")
- def test_uses_cached_window_when_result_count_meets_threshold(self, patch_query_with_columns, mock_cache):
+ @patch("posthog.models.event.legacy_events_query.cache")
+ @patch("posthog.models.event.legacy_events_query._execute_events_list_query")
+ def test_uses_cached_window_when_result_count_meets_threshold(self, patch_execute_query, mock_cache):
# Cached window with result_count >= half_limit (60 >= 50 for limit=100)
mock_cache.get.return_value = {"window": 3600, "result_count": 60}
- patch_query_with_columns.return_value = [
- {
- "uuid": "event",
- "event": "test",
- "properties": "{}",
- "timestamp": timezone.now(),
- "team_id": str(self.team.pk),
- "distinct_id": "1",
- "elements_chain": "",
- }
- for _ in range(60)
- ]
+ patch_execute_query.return_value = (
+ [
+ {
+ "uuid": "event",
+ "event": "test",
+ "properties": "{}",
+ "timestamp": timezone.now(),
+ "team_id": str(self.team.pk),
+ "distinct_id": "1",
+ "elements_chain": "",
+ }
+ for _ in range(60)
+ ],
+ False,
+ )
self.client.get(f"/api/projects/{self.team.id}/events/")
# Should only call once since cached window returned enough results
- assert patch_query_with_columns.call_count == 1
+ assert patch_execute_query.call_count == 1
# Should NOT update cache when data is identical (optimization)
mock_cache.set.assert_not_called()
@patch("posthog.api.event.EVENT_LIST_MAX_LIMIT", 6000)
- @patch("posthog.api.event.cache")
- @patch("posthog.api.event.query_events_list")
- def test_ignores_cached_window_when_result_count_below_threshold(self, mock_query_events_list, mock_cache):
+ @patch("posthog.models.event.legacy_events_query.cache")
+ @patch("posthog.models.event.legacy_events_query.LegacyEventsListQuery.run_page")
+ def test_ignores_cached_window_when_result_count_below_threshold(self, mock_run_page, mock_cache):
"""
This test verifies the fix for the cache key bug where different limits
could share the same cache key but have different half_limit thresholds.
@@ -1338,7 +1445,7 @@ class TestEventListTimeWindowOptimization(ClickhouseTestMixin, APIBaseTest):
mock_cache.get.return_value = {"window": 3600, "result_count": 2700}
# Return 3500 results (enough for limit=6000's half_limit=3000)
- mock_query_events_list.return_value = (
+ mock_run_page.return_value = (
[
{
"uuid": f"event-{i}",
@@ -1351,6 +1458,7 @@ class TestEventListTimeWindowOptimization(ClickhouseTestMixin, APIBaseTest):
}
for i in range(3500)
],
+ False, # has_more
60, # applied_window
)
@@ -1359,7 +1467,7 @@ class TestEventListTimeWindowOptimization(ClickhouseTestMixin, APIBaseTest):
# Cache result_count (2700) < half_limit (3000), so cache should be ignored.
# Should start from smallest window (60s), not cached 3600s.
- first_call_kwargs = mock_query_events_list.call_args_list[0][1]
+ first_call_kwargs = mock_run_page.call_args_list[0][1]
assert first_call_kwargs["time_window_seconds"] == 60 # Not 3600
# Should cache new successful window with correct structure
@@ -1367,16 +1475,16 @@ class TestEventListTimeWindowOptimization(ClickhouseTestMixin, APIBaseTest):
cached_data = mock_cache.set.call_args[0][1]
assert cached_data == {"window": 60, "result_count": 3500}
- @patch("posthog.api.event.cache")
- @patch("posthog.api.event.query_events_list")
- def test_backwards_compat_uses_old_integer_cache_format(self, mock_query_events_list, mock_cache):
+ @patch("posthog.models.event.legacy_events_query.cache")
+ @patch("posthog.models.event.legacy_events_query.LegacyEventsListQuery.run_page")
+ def test_backwards_compat_uses_old_integer_cache_format(self, mock_run_page, mock_cache):
"""
Old cache entries are just integers (the window). For backwards compatibility,
we use these directly (we can't know if they have enough results).
"""
mock_cache.get.return_value = 3600 # Old format: just the window integer
- mock_query_events_list.return_value = (
+ mock_run_page.return_value = (
[
{
"uuid": "event",
@@ -1389,13 +1497,14 @@ class TestEventListTimeWindowOptimization(ClickhouseTestMixin, APIBaseTest):
}
for _ in range(50)
],
+ False, # has_more
3600, # applied_window
)
self.client.get(f"/api/projects/{self.team.id}/events/")
# Should use cached window (3600) first due to backwards compatibility
- first_call_kwargs = mock_query_events_list.call_args_list[0][1]
+ first_call_kwargs = mock_run_page.call_args_list[0][1]
assert first_call_kwargs["time_window_seconds"] == 3600
# Should update cache to new format
@@ -1403,89 +1512,101 @@ class TestEventListTimeWindowOptimization(ClickhouseTestMixin, APIBaseTest):
cached_data = mock_cache.set.call_args[0][1]
assert cached_data == {"window": 3600, "result_count": 50}
- @patch("posthog.api.event.cache")
- @patch("posthog.models.event.query_event_list.insight_query_with_columns")
- def test_does_not_cache_when_fallback_used(self, patch_query_with_columns, mock_cache):
+ @patch("posthog.models.event.legacy_events_query.cache")
+ @patch("posthog.models.event.legacy_events_query._execute_events_list_query")
+ def test_does_not_cache_when_fallback_used(self, patch_execute_query, mock_cache):
mock_cache.get.return_value = None
# Return too few results to trigger fallback
- patch_query_with_columns.return_value = [
- {
- "uuid": "event",
- "event": "test",
- "properties": "{}",
- "timestamp": timezone.now(),
- "team_id": str(self.team.pk),
- "distinct_id": "1",
- "elements_chain": "",
- }
- ]
+ patch_execute_query.return_value = (
+ [
+ {
+ "uuid": "event",
+ "event": "test",
+ "properties": "{}",
+ "timestamp": timezone.now(),
+ "team_id": str(self.team.pk),
+ "distinct_id": "1",
+ "elements_chain": "",
+ }
+ ],
+ False,
+ )
self.client.get(f"/api/projects/{self.team.id}/events/")
# Should not cache anything when fallback is used
mock_cache.set.assert_not_called()
- @patch("posthog.models.event.query_event_list.insight_query_with_columns")
- def test_only_tries_windows_shorter_than_request(self, patch_query_with_columns):
+ @patch("posthog.models.event.legacy_events_query._execute_events_list_query")
+ def test_only_tries_windows_shorter_than_request(self, patch_execute_query):
# Request a 10-minute window (600 seconds)
# Should only try windows < 600: [60, 300] (2 windows) + fallback
- patch_query_with_columns.return_value = [
- {
- "uuid": "event",
- "event": "test",
- "properties": "{}",
- "timestamp": timezone.now(),
- "team_id": str(self.team.pk),
- "distinct_id": "1",
- "elements_chain": "",
- }
- ]
+ patch_execute_query.return_value = (
+ [
+ {
+ "uuid": "event",
+ "event": "test",
+ "properties": "{}",
+ "timestamp": timezone.now(),
+ "team_id": str(self.team.pk),
+ "distinct_id": "1",
+ "elements_chain": "",
+ }
+ ],
+ False,
+ )
# 10-minute window
self.client.get(f"/api/projects/{self.team.id}/events/?after=2024-01-01T00:00:00Z&before=2024-01-01T00:10:00Z")
# Should try [60, 300] + fallback = 3 calls
- assert patch_query_with_columns.call_count == 3
+ assert patch_execute_query.call_count == 3
- @patch("posthog.models.event.query_event_list.insight_query_with_columns")
- def test_no_window_optimization_for_small_request_range(self, patch_query_with_columns):
+ @patch("posthog.models.event.legacy_events_query._execute_events_list_query")
+ def test_no_window_optimization_for_small_request_range(self, patch_execute_query):
# Request a 30-second window - smaller than smallest optimization window (60s)
# Should skip all windows and go straight to full request
- patch_query_with_columns.return_value = [
- {
- "uuid": "event",
- "event": "test",
- "properties": "{}",
- "timestamp": timezone.now(),
- "team_id": str(self.team.pk),
- "distinct_id": "1",
- "elements_chain": "",
- }
- ]
+ patch_execute_query.return_value = (
+ [
+ {
+ "uuid": "event",
+ "event": "test",
+ "properties": "{}",
+ "timestamp": timezone.now(),
+ "team_id": str(self.team.pk),
+ "distinct_id": "1",
+ "elements_chain": "",
+ }
+ ],
+ False,
+ )
self.client.get(f"/api/projects/{self.team.id}/events/?after=2024-01-01T00:00:00Z&before=2024-01-01T00:00:30Z")
# No windows < 30s, so straight to fallback = 1 call
- assert patch_query_with_columns.call_count == 1
+ assert patch_execute_query.call_count == 1
- @patch("posthog.api.event.cache")
- @patch("posthog.models.event.query_event_list.insight_query_with_columns")
- def test_different_cache_keys_for_different_filters(self, patch_query_with_columns, mock_cache):
+ @patch("posthog.models.event.legacy_events_query.cache")
+ @patch("posthog.models.event.legacy_events_query._execute_events_list_query")
+ def test_different_cache_keys_for_different_filters(self, patch_execute_query, mock_cache):
mock_cache.get.return_value = None
- patch_query_with_columns.return_value = [
- {
- "uuid": "event",
- "event": "test",
- "properties": "{}",
- "timestamp": timezone.now(),
- "team_id": str(self.team.pk),
- "distinct_id": "1",
- "elements_chain": "",
- }
- for _ in range(50)
- ]
+ patch_execute_query.return_value = (
+ [
+ {
+ "uuid": "event",
+ "event": "test",
+ "properties": "{}",
+ "timestamp": timezone.now(),
+ "team_id": str(self.team.pk),
+ "distinct_id": "1",
+ "elements_chain": "",
+ }
+ for _ in range(50)
+ ],
+ False,
+ )
# Request without filters
self.client.get(f"/api/projects/{self.team.id}/events/")
@@ -1514,9 +1635,9 @@ class TestEventListTimeWindowOptimization(ClickhouseTestMixin, APIBaseTest):
("many_results", 5),
]
)
- @patch("posthog.api.event.cache")
- @patch("posthog.models.event.query_event_list.insight_query_with_columns")
- def test_asc_order_skips_window_optimization(self, _name, num_results, patch_query_with_columns, mock_cache):
+ @patch("posthog.models.event.legacy_events_query.cache")
+ @patch("posthog.models.event.legacy_events_query._execute_events_list_query")
+ def test_asc_order_skips_window_optimization(self, _name, num_results, patch_execute_query, mock_cache):
"""
ASC order queries skip window optimization entirely.
@@ -1527,21 +1648,24 @@ class TestEventListTimeWindowOptimization(ClickhouseTestMixin, APIBaseTest):
- No caching (nothing to cache)
"""
mock_cache.get.return_value = None
- patch_query_with_columns.return_value = [
- {
- "uuid": f"event-{i}",
- "event": "test",
- "properties": "{}",
- "timestamp": timezone.now(),
- "team_id": str(self.team.pk),
- "distinct_id": "1",
- "elements_chain": "",
- }
- for i in range(num_results)
- ]
+ patch_execute_query.return_value = (
+ [
+ {
+ "uuid": f"event-{i}",
+ "event": "test",
+ "properties": "{}",
+ "timestamp": timezone.now(),
+ "team_id": str(self.team.pk),
+ "distinct_id": "1",
+ "elements_chain": "",
+ }
+ for i in range(num_results)
+ ],
+ False,
+ )
response = self.client.get(f"/api/projects/{self.team.id}/events/?orderBy={json.dumps(['timestamp'])}")
- assert patch_query_with_columns.call_count == 1
+ assert patch_execute_query.call_count == 1
assert len(response.json()["results"]) == num_results
mock_cache.set.assert_not_called()
diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.py
index 954ff1dd11c1..9861829a3d67 100644
--- a/posthog/hogql/test/test_direct_postgres_query.py
+++ b/posthog/hogql/test/test_direct_postgres_query.py
@@ -25,6 +25,8 @@ from posthog.hogql.errors import ExposedHogQLError, QueryError
from posthog.hogql.escape_sql import escape_postgres_identifier
from posthog.hogql.query import HogQLQueryExecutor
+from posthog.models import Team
+
from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import SSL_REQUIRED_AFTER_DATE
@@ -1269,8 +1271,12 @@ class TestDirectPostgresQuery(APIBaseTest):
@override_settings(CLOUD_DEPLOYMENT="DEV")
@patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")
def test_execute_direct_postgres_query_blocks_internal_host(self, mock_connect):
+ # team id 2 (US) / 1 (EU) are allowlisted to reach internal IPs, so use an explicit
+ # non-allowlisted id — otherwise this flakes when pytest-split orders the test first in
+ # its shard and self.team happens to be assigned pk 2, bypassing the SSRF block.
+ team = Team.objects.create(id=984961485, name="ssrf_test_team", organization=self.organization)
source = ExternalDataSource.objects.create(
- team=self.team,
+ team=team,
source_id="source_id",
connection_id="connection_id",
status=ExternalDataSource.Status.COMPLETED,
@@ -1290,7 +1296,7 @@ class TestDirectPostgresQuery(APIBaseTest):
DataWarehouseTable.objects.create(
name="posthog_dashboard",
format="Parquet",
- team=self.team,
+ team=team,
external_data_source=source,
url_pattern="direct://postgres",
columns={
@@ -1300,7 +1306,7 @@ class TestDirectPostgresQuery(APIBaseTest):
executor = HogQLQueryExecutor(
query="SELECT id FROM posthog_dashboard LIMIT 1",
- team=self.team,
+ team=team,
connection_id=str(source.id),
)
diff --git a/posthog/models/event/legacy_events_query.py b/posthog/models/event/legacy_events_query.py
new file mode 100644
index 000000000000..57f0a32a3169
--- /dev/null
+++ b/posthog/models/event/legacy_events_query.py
@@ -0,0 +1,297 @@
+import uuid
+import random
+import builtins
+from datetime import datetime, timedelta
+from typing import Optional, cast
+
+from django.conf import settings
+from django.core.cache import cache
+
+from posthog.schema import EventsQuery, HogQLQueryModifiers
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.client.limit import get_events_list_rate_limiter
+from posthog.hogql_queries.events_query_runner import EventsQueryRunner
+from posthog.models.team import Team
+from posthog.models.user import User
+from posthog.utils import generate_short_id, relative_date_parse
+
+from products.actions.backend.models.action import Action
+
+# Columns the events list/retrieve endpoints read. The order is the contract for zipping HogQL
+# result rows back into the dict shape `ClickhouseEventSerializer` expects. Deliberately NOT "*":
+# that triggers the runner's session-recording lookup and element expansion, which this endpoint's
+# serializer does its own version of.
+EVENT_LIST_SELECT_COLUMNS = ["uuid", "event", "properties", "timestamp", "distinct_id", "elements_chain"]
+
+# Progressive time windows in seconds: 1min, 5min, 15min, 1hr, 6hr, 24hr.
+EVENT_LIST_TIME_WINDOWS = [60, 300, 900, 3600, 21600, 86400]
+EVENT_LIST_CACHE_TTL = 86400 # 24 hours
+EVENT_LIST_CACHE_KEY_PREFIX = "event_list_good_period"
+
+
+def _get_limit_size_category(limit: int) -> str:
+ """Group limits into size categories to bound cache-key cardinality."""
+ if limit < 1000:
+ return "s"
+ elif limit < 10000:
+ return "m"
+ return "l"
+
+
+def _get_event_list_cache_key(team_id: int, has_event_filter: bool, has_distinct_id: bool, limit: int) -> str:
+ """Cache key for the progressive-window optimization.
+
+ The cache stores ``{"window": int, "result_count": int}`` so a cached window is only reused
+ when its result_count clears the current request's half-limit threshold — otherwise a window
+ that succeeded for a small limit would be wrongly reused for a larger one. Size categories
+ (s/m/l) instead of exact limits bound the key cardinality to ~3 per team/filter combination.
+ """
+ event_flag = "1" if has_event_filter else "0"
+ distinct_id_flag = "1" if has_distinct_id else "0"
+ return f"{EVENT_LIST_CACHE_KEY_PREFIX}:{team_id}:{event_flag}:{distinct_id_flag}:{_get_limit_size_category(limit)}"
+
+
+def _execute_events_list_query(runner: EventsQueryRunner, database: Database) -> tuple[builtins.list[dict], bool]:
+ """Execute the events-list HogQL query and return ``(page_rows, has_more)``.
+
+ Split out from `LegacyEventsListQuery.run_page` so the progressive-window probing can be tested
+ against the real window/date logic while stubbing only the ClickHouse round-trip. The pre-built
+ `database` is handed to the executor so it isn't rebuilt per probe.
+ """
+ runner.paginator.execute_hogql_query(
+ runner.to_query(),
+ query_type="events_list",
+ team=runner.team,
+ workload=Workload.OFFLINE,
+ settings=HogQLGlobalSettings(max_threads=settings.CLICKHOUSE_EVENT_LIST_MAX_THREADS),
+ modifiers=runner.modifiers,
+ timings=runner.timings,
+ user=runner.user,
+ context=HogQLContext(team=runner.team, database=database, enable_select_queries=True),
+ )
+ rows = [dict(zip(EVENT_LIST_SELECT_COLUMNS, row)) for row in runner.paginator.results]
+ return rows, runner.paginator.has_more()
+
+
+def get_one_event(team: Team, pk: str) -> Optional[dict]:
+ """Fetch a single event by uuid for the events retrieve endpoint, or None if it doesn't exist."""
+ query = ast.SelectQuery(
+ select=[ast.Field(chain=[column]) for column in EVENT_LIST_SELECT_COLUMNS],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["uuid"]),
+ right=ast.Constant(value=uuid.UUID(pk)),
+ ),
+ )
+ result = execute_hogql_query(query, team=team, query_type="event_detail")
+ if not result.results:
+ return None
+ return dict(zip(EVENT_LIST_SELECT_COLUMNS, result.results[0]))
+
+
+class LegacyEventsListQuery:
+ """Backing query for the deprecated events list REST API (`posthog/api/event.py`).
+
+ Translates the endpoint's loose query params into a typed HogQL `EventsQuery` and runs it
+ through `EventsQueryRunner`, owning the progressive-window probing and its result-count cache.
+ The HogQL schema (database + modifiers) is built once here and reused across every window probe.
+
+ New code should build an `EventsQuery` (or use the `/query` endpoint) directly, not this.
+ """
+
+ def __init__(self, team: Team, user: Optional[User]) -> None:
+ self.team = team
+ self.user = user
+ self.modifiers: HogQLQueryModifiers = create_default_modifiers_for_team(team)
+ self.database = Database.create_for(team=team, user=user, modifiers=self.modifiers)
+
+ def run(
+ self,
+ *,
+ limit: int,
+ offset: int,
+ order: str,
+ before: Optional[str],
+ after: Optional[str],
+ event: Optional[str],
+ person_id: Optional[str],
+ distinct_id: Optional[str],
+ properties: "builtins.list[dict] | dict | None",
+ action_id: Optional[str],
+ ) -> tuple[builtins.list[dict], bool]:
+ """Return one page of events as ``(rows, has_more)``.
+
+ Probes progressively larger time windows (see `EVENT_LIST_TIME_WINDOWS`) so a recent-events
+ request doesn't scan all history, stopping at the first window that returns at least half a
+ page and caching it; falls back to the request's full range otherwise. Runs under the events
+ rate limiter, on the OFFLINE workload.
+ """
+ cache_key = _get_event_list_cache_key(self.team.pk, bool(event), bool(distinct_id), limit)
+ cached_data = cache.get(cache_key)
+
+ request_window_seconds: Optional[int] = None
+ if before and after:
+ try:
+ tzinfo = self.team.timezone_info
+ request_window_seconds = int(
+ (relative_date_parse(before, tzinfo) - relative_date_parse(after, tzinfo)).total_seconds()
+ )
+ except (ValueError, TypeError):
+ pass
+
+ # Only probe windows shorter than the request's own range.
+ windows_to_try = [
+ w for w in EVENT_LIST_TIME_WINDOWS if request_window_seconds is None or w < request_window_seconds
+ ]
+ half_limit = max(limit // 2, 1)
+
+ # Reuse a cached window only if it returned enough results for this request's threshold.
+ cached_window = None
+ if cached_data and isinstance(cached_data, dict):
+ if cached_data.get("result_count", 0) >= half_limit:
+ cached_window = cached_data.get("window")
+ elif cached_data and isinstance(cached_data, int):
+ cached_window = cached_data # legacy cache format: bare window integer
+ if cached_window and cached_window in windows_to_try:
+ windows_to_try.remove(cached_window)
+ windows_to_try.insert(0, cached_window)
+
+ page_kwargs: dict = {
+ "limit": limit,
+ "offset": offset,
+ "order": order,
+ "before": before,
+ "after": after,
+ "event": event,
+ "person_id": person_id,
+ "distinct_id": distinct_id,
+ "properties": properties,
+ "action_id": action_id,
+ }
+
+ with get_events_list_rate_limiter().run(team_id=self.team.pk, task_id=generate_short_id()):
+ rows: builtins.list[dict] = []
+ has_more = False
+ successful_window: Optional[int] = None
+ applied_window: Optional[int] = None
+
+ for window in windows_to_try:
+ rows, has_more, applied_window = self.run_page(**page_kwargs, time_window_seconds=window)
+ if applied_window is None: # window not applicable (e.g. ASC order) — don't keep probing
+ break
+ if len(rows) >= half_limit:
+ successful_window = window
+ break
+
+ if successful_window:
+ new_cache_data = {"window": successful_window, "result_count": len(rows)}
+ if new_cache_data != cached_data:
+ cache.set(cache_key, new_cache_data, EVENT_LIST_CACHE_TTL)
+ elif applied_window is not None or not windows_to_try:
+ # Windows were applied but came up short, or there were none — run the full range.
+ rows, has_more, applied_window = self.run_page(**page_kwargs)
+
+ return rows, has_more
+
+ def run_page(
+ self,
+ *,
+ limit: int,
+ offset: int,
+ order: str,
+ before: Optional[str],
+ after: Optional[str],
+ event: Optional[str],
+ person_id: Optional[str],
+ distinct_id: Optional[str],
+ properties: "builtins.list[dict] | dict | None",
+ action_id: Optional[str],
+ time_window_seconds: Optional[int] = None,
+ ) -> tuple[builtins.list[dict], bool, Optional[int]]:
+ """Run a single window probe.
+
+ Returns the page rows (already trimmed to `limit`), whether more rows exist, and the time
+ window that was applied (`None` when the request's own date range was used).
+ """
+ tzinfo = self.team.timezone_info
+
+ # Resolve the [after_dt, before_dt) bounds. `before` defaults to just past now (so events
+ # ingested a moment ago aren't excluded); `after` stays open unless requested.
+ # PATCH_EVENT_LIST_MAX_OFFSET clamps this deprecated endpoint's ClickHouse cost as a graduated
+ # rollout (0 = off, 1 = migration, 2 = enabled; see settings/data_stores.py): at 2 a missing
+ # `after` defaults to before-24h, and a range over a year is rejected (always at 2, ~1% at 1).
+ before_dt = relative_date_parse(before, tzinfo) if before else datetime.now(tzinfo) + timedelta(seconds=5)
+ if after:
+ after_dt: Optional[datetime] = relative_date_parse(after, tzinfo)
+ elif settings.PATCH_EVENT_LIST_MAX_OFFSET > 1:
+ after_dt = before_dt - timedelta(hours=24)
+ else:
+ after_dt = None
+
+ if settings.PATCH_EVENT_LIST_MAX_OFFSET > 0 and after_dt is not None:
+ if (before_dt - after_dt) > timedelta(days=366) and (
+ settings.PATCH_EVENT_LIST_MAX_OFFSET > 1 or random.random() < 0.01
+ ):
+ raise ValueError("Date range cannot exceed 1 year")
+
+ applied_window_seconds: Optional[int] = None
+ if (
+ order == "DESC"
+ and time_window_seconds is not None
+ and (after_dt is None or (before_dt - after_dt).total_seconds() > time_window_seconds)
+ ):
+ after_dt = before_dt - timedelta(seconds=time_window_seconds)
+ applied_window_seconds = time_window_seconds
+
+ # Match the legacy behaviour for actions with no match groups (or that no longer exist):
+ # an empty result, not an error. The runner would otherwise raise. A malformed action_id
+ # is left to fail (int() raises) — bad input should error, not silently return nothing.
+ if action_id:
+ try:
+ action = Action.objects.get(pk=int(action_id), team__project_id=self.team.project_id)
+ except Action.DoesNotExist:
+ return [], False, applied_window_seconds
+ if not action.steps:
+ return [], False, applied_window_seconds
+
+ # A flat list of leaf filters goes through `properties`; a property group goes through
+ # `fixedProperties`, where the runner's `property_to_expr` preserves its nested AND/OR.
+ where_properties: builtins.list[dict] = []
+ fixed_properties: builtins.list[dict] = []
+ if isinstance(properties, dict):
+ fixed_properties = [properties]
+ elif properties:
+ where_properties = list(properties)
+ if distinct_id is not None:
+ where_properties.append(
+ {"type": "event_metadata", "key": "distinct_id", "value": distinct_id, "operator": "exact"}
+ )
+
+ events_query = EventsQuery(
+ select=EVENT_LIST_SELECT_COLUMNS,
+ before=before_dt.isoformat(),
+ # "all" disables the runner's default 24h lower bound: with no `after` and no window,
+ # the query has no lower timestamp bound at all.
+ after=after_dt.isoformat() if after_dt is not None else "all",
+ event=event or None,
+ personId=str(person_id) if person_id else None,
+ actionId=int(action_id) if action_id else None,
+ properties=cast("builtins.list[dict[str, object]]", where_properties) if where_properties else None,
+ fixedProperties=cast("builtins.list[dict[str, object]]", fixed_properties) if fixed_properties else None,
+ orderBy=[f"timestamp {order}"],
+ limit=limit,
+ offset=offset,
+ )
+
+ runner = EventsQueryRunner(query=events_query, team=self.team, user=self.user, modifiers=self.modifiers)
+ rows, has_more = _execute_events_list_query(runner, self.database)
+ return rows, has_more, applied_window_seconds
diff --git a/posthog/models/event/query_event_list.py b/posthog/models/event/query_event_list.py
deleted file mode 100644
index f33d40f5ad52..000000000000
--- a/posthog/models/event/query_event_list.py
+++ /dev/null
@@ -1,191 +0,0 @@
-import random
-from datetime import datetime, timedelta
-from typing import Optional, Union
-from zoneinfo import ZoneInfo
-
-from django.conf import settings
-
-from dateutil.parser import isoparse
-
-from posthog.hogql.constants import DEFAULT_RETURNED_ROWS
-from posthog.hogql.context import HogQLContext
-
-from posthog.clickhouse.client.connection import Workload
-from posthog.models import Filter, Team
-from posthog.models.event.sql import (
- SELECT_EVENT_BY_TEAM_AND_CONDITIONS_FILTERS_SQL,
- SELECT_EVENT_BY_TEAM_AND_CONDITIONS_SQL,
-)
-from posthog.models.person.person import MAX_LIMIT_DISTINCT_IDS, get_distinct_ids_for_subquery
-from posthog.models.person.util import get_person_by_pk_or_uuid
-from posthog.models.property.util import parse_prop_grouped_clauses
-from posthog.personhog_client.caller_tag import personhog_caller_tag
-from posthog.queries.insight import insight_query_with_columns
-from posthog.utils import relative_date_parse
-
-from products.actions.backend.models.action import Action
-from products.actions.backend.models.util import format_action_filter
-
-
-def parse_timestamp(timestamp: str, tzinfo: ZoneInfo) -> datetime:
- try:
- parsed = isoparse(timestamp)
- if parsed.tzinfo is None:
- return parsed.replace(tzinfo=tzinfo)
- return parsed
- except ValueError:
- return relative_date_parse(timestamp, tzinfo)
-
-
-def parse_request_params(
- conditions: dict[str, Union[None, str, list[str]]], team: Team, tzinfo: ZoneInfo
-) -> tuple[str, dict]:
- result = ""
- params: dict[str, Union[str, list[str]]] = {}
- for k, v in conditions.items():
- if not isinstance(v, str):
- continue
- if k == "after":
- result += "AND timestamp > %(after)s "
- params.update({"after": v})
- elif k == "before":
- result += "AND timestamp < %(before)s "
- params.update({"before": v})
- elif k == "person_id":
- result += """AND distinct_id IN (%(distinct_ids)s) """
- with personhog_caller_tag("persons/event-list"):
- person = get_person_by_pk_or_uuid(team.pk, v, distinct_id_limit=MAX_LIMIT_DISTINCT_IDS)
- params.update({"distinct_ids": get_distinct_ids_for_subquery(person, team)})
- elif k == "distinct_id":
- result += "AND distinct_id = %(distinct_id)s "
- params.update({"distinct_id": v})
- elif k == "event":
- result += "AND event = %(event)s "
- params.update({"event": v})
- return result, params
-
-
-def query_events_list(
- filter: Filter,
- team: Team,
- request_get_query_dict: dict,
- order_by: list[str],
- action_id: Optional[str],
- unbounded_date_from: bool = False,
- limit: int = DEFAULT_RETURNED_ROWS,
- offset: int = 0,
- time_window_seconds: Optional[int] = None,
-) -> tuple[list, Optional[int]]:
- # Note: This code is inefficient and problematic, see https://github.com/PostHog/posthog/issues/13485 for details.
- # To isolate its impact from rest of the queries its queries are run on different nodes as part of "offline" workloads.
- hogql_context = HogQLContext(within_non_hogql_query=True, team_id=team.pk, enable_select_queries=True)
-
- limit += 1
- limit_sql = "LIMIT %(limit)s"
-
- if offset > 0:
- limit_sql += " OFFSET %(offset)s"
-
- order = "DESC" if len(order_by) == 1 and order_by[0] == "-timestamp" else "ASC"
-
- if request_get_query_dict.get("before"):
- request_get_query_dict["before"] = parse_timestamp(request_get_query_dict["before"], team.timezone_info)
- else:
- request_get_query_dict["before"] = datetime.now(team.timezone_info) + timedelta(seconds=5)
-
- if request_get_query_dict.get("after"):
- request_get_query_dict["after"] = parse_timestamp(request_get_query_dict["after"], team.timezone_info)
- elif settings.PATCH_EVENT_LIST_MAX_OFFSET > 1:
- request_get_query_dict["after"] = request_get_query_dict["before"] - timedelta(hours=24)
-
- if settings.PATCH_EVENT_LIST_MAX_OFFSET > 0 and request_get_query_dict.get("after"):
- date_range = request_get_query_dict["before"] - request_get_query_dict["after"]
- if date_range > timedelta(days=366) and (settings.PATCH_EVENT_LIST_MAX_OFFSET > 1 or random.random() < 0.01):
- raise ValueError("Date range cannot exceed 1 year")
-
- applied_window_seconds: Optional[int] = None
- if (
- not unbounded_date_from
- and order == "DESC"
- and time_window_seconds is not None
- and (
- not request_get_query_dict.get("after")
- or (request_get_query_dict["before"] - request_get_query_dict["after"]).total_seconds()
- > time_window_seconds
- )
- ):
- # Apply the specified time window to limit the query range
- request_get_query_dict["after"] = request_get_query_dict["before"] - timedelta(seconds=time_window_seconds)
- applied_window_seconds = time_window_seconds
-
- request_get_query_dict["before"] = request_get_query_dict["before"].strftime("%Y-%m-%d %H:%M:%S.%f")
- if request_get_query_dict.get("after"):
- request_get_query_dict["after"] = request_get_query_dict["after"].strftime("%Y-%m-%d %H:%M:%S.%f")
-
- conditions, condition_params = parse_request_params(
- request_get_query_dict,
- team,
- tzinfo=team.timezone_info,
- )
-
- prop_filters, prop_filter_params = parse_prop_grouped_clauses(
- team_id=team.pk,
- property_group=filter.property_groups,
- has_person_id_joined=False,
- hogql_context=hogql_context,
- )
-
- if action_id:
- try:
- action = Action.objects.get(pk=action_id, team__project_id=team.project_id)
- if not action.steps:
- return [], applied_window_seconds
- except Action.DoesNotExist:
- return [], applied_window_seconds
-
- action_query, params = format_action_filter(team_id=team.pk, action=action, hogql_context=hogql_context)
- prop_filters += " AND {}".format(action_query)
- prop_filter_params = {**prop_filter_params, **params}
-
- if prop_filters != "":
- return (
- insight_query_with_columns(
- SELECT_EVENT_BY_TEAM_AND_CONDITIONS_FILTERS_SQL.format(
- conditions=conditions,
- limit=limit_sql,
- filters=prop_filters,
- order=order,
- ),
- {
- "team_id": team.pk,
- "limit": limit,
- "offset": offset,
- **condition_params,
- **prop_filter_params,
- **hogql_context.values,
- },
- query_type="events_list",
- workload=Workload.OFFLINE,
- team_id=team.pk,
- settings={"max_threads": settings.CLICKHOUSE_EVENT_LIST_MAX_THREADS},
- ),
- applied_window_seconds,
- )
- else:
- return (
- insight_query_with_columns(
- SELECT_EVENT_BY_TEAM_AND_CONDITIONS_SQL.format(conditions=conditions, limit=limit_sql, order=order),
- {
- "team_id": team.pk,
- "limit": limit,
- "offset": offset,
- **condition_params,
- **hogql_context.values,
- },
- query_type="events_list",
- workload=Workload.OFFLINE,
- team_id=team.pk,
- settings={"max_threads": settings.CLICKHOUSE_EVENT_LIST_MAX_THREADS},
- ),
- applied_window_seconds,
- )
diff --git a/posthog/models/event/sql.py b/posthog/models/event/sql.py
index c1d479654171..e2d2aac4d41b 100644
--- a/posthog/models/event/sql.py
+++ b/posthog/models/event/sql.py
@@ -581,54 +581,6 @@ WHERE
LIMIT 10
"""
-SELECT_EVENT_BY_TEAM_AND_CONDITIONS_SQL = """
-SELECT
- uuid,
- event,
- properties,
- timestamp,
- team_id,
- distinct_id,
- elements_chain,
- created_at
-FROM
- events
-where team_id = %(team_id)s
-{conditions}
-ORDER BY timestamp {order} {limit}
-"""
-
-SELECT_EVENT_BY_TEAM_AND_CONDITIONS_FILTERS_SQL = """
-SELECT
- uuid,
- event,
- properties,
- timestamp,
- team_id,
- distinct_id,
- elements_chain,
- created_at
-FROM events
-WHERE
-team_id = %(team_id)s
-{conditions}
-{filters}
-ORDER BY timestamp {order} {limit}
-"""
-
-SELECT_ONE_EVENT_SQL = """
-SELECT
- uuid,
- event,
- properties,
- timestamp,
- team_id,
- distinct_id,
- elements_chain,
- created_at
-FROM events WHERE uuid = %(event_id)s AND team_id = %(team_id)s
-"""
-
NULL_SQL = """
-- Creates zero values for all date axis ticks for the given date_from, date_to range
SELECT toUInt16(0) AS total, {date_to_truncated} - {interval_func}(number) AS day_start
diff --git a/posthog/models/event/test_query_event_list_personhog.py b/posthog/models/event/test_query_event_list_personhog.py
deleted file mode 100644
index 190e0a5cb296..000000000000
--- a/posthog/models/event/test_query_event_list_personhog.py
+++ /dev/null
@@ -1,37 +0,0 @@
-"""Tests that parse_request_params person lookups produce identical results."""
-
-from zoneinfo import ZoneInfo
-
-from posthog.test.base import BaseTest
-
-from posthog.models.event.query_event_list import parse_request_params
-from posthog.test.personhog_fake import get_active_fake
-from posthog.test.persons import create_person
-
-UUID_NONEXISTENT = "550e8400-e29b-41d4-a716-446655440000"
-
-
-class TestParseRequestParamsPersonRouting(BaseTest):
- def test_uuid_person_id_resolves_distinct_ids(self):
- person = create_person(team=self.team, distinct_ids=["id1", "id2"])
-
- _result, params = parse_request_params({"person_id": str(person.uuid)}, self.team, ZoneInfo("UTC"))
-
- assert set(params["distinct_ids"]) == {"id1", "id2"}
- get_active_fake().assert_called("get_person_by_uuid")
- get_active_fake().assert_called("get_distinct_ids_for_person")
-
- def test_uuid_person_id_not_found_returns_empty(self):
- _result, params = parse_request_params({"person_id": UUID_NONEXISTENT}, self.team, ZoneInfo("UTC"))
-
- assert params["distinct_ids"] == []
- get_active_fake().assert_called("get_person_by_uuid")
-
- def test_integer_person_id_resolves_distinct_ids(self):
- person = create_person(team=self.team, distinct_ids=["id1", "id2"])
-
- _result, params = parse_request_params({"person_id": str(person.pk)}, self.team, ZoneInfo("UTC"))
-
- assert set(params["distinct_ids"]) == {"id1", "id2"}
- get_active_fake().assert_not_called("get_person_by_uuid")
- get_active_fake().assert_called("get_person")
diff --git a/posthog/queries/insight.py b/posthog/queries/insight.py
index 55a29a8627f1..9c77059c9db4 100644
--- a/posthog/queries/insight.py
+++ b/posthog/queries/insight.py
@@ -2,7 +2,7 @@ from typing import TYPE_CHECKING, Optional
from rest_framework.exceptions import ValidationError
-from posthog.clickhouse.client import query_with_columns, sync_execute
+from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import tag_queries
from posthog.errors import ExposedCHQueryError
@@ -28,21 +28,6 @@ def insight_sync_execute(
raise ValidationError(str(e), e.code_name)
-# Wrapper around `query_with_columns`
-def insight_query_with_columns(
- query,
- args=None,
- *,
- query_type: str,
- filter: Optional["FilterType"] = None,
- team_id: int,
- **kwargs,
-):
- _tag_query(query, query_type, filter)
-
- return query_with_columns(query, args=args, team_id=team_id, **kwargs)
-
-
def _tag_query(query, query_type, filter: Optional["FilterType"]):
tag_queries(
query_type=query_type,
diff --git a/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr b/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr
index 0839c952c78f..a1c0325ab25a 100644
--- a/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr
+++ b/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr
@@ -11,6 +11,14 @@
OR query @? '$.** ? (
@.kind == "InsightVizNode" &&
(!exists(@.version) || @.version == null || @.version < 4)
+ )'
+ OR query @? '$.** ? (
+ @.kind == "RetentionQuery" &&
+ (!exists(@.version) || @.version == null || @.version < 2)
+ )'
+ OR query @? '$.** ? (
+ @.kind == "StickinessQuery" &&
+ (!exists(@.version) || @.version == null || @.version < 2)
)'
OR query @? '$.** ? (
@.kind == "TrendsQuery" &&