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.

chore: remove dead legacy person funnel/trends endpoints (#73064)

Andy Zhao2c74caa9889b
diff --git a/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel_person.ambr b/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel_person.ambr
deleted file mode 100644
index 00afb71f7b90..000000000000
--- a/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel_person.ambr
+++ /dev/null
@@ -1,155 +0,0 @@
-# serializer version: 1
-# name: TestFunnelPerson.test_funnel_actors_with_groups_search
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT source.actor_id AS actor_id
- FROM
- (SELECT aggregation_target AS actor_id,
- actor_id AS key
- FROM
- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,
- [''] AS prop,
- arrayJoin(aggregate_funnel(3, 1209600, 'first_touch', 'ordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), equals(x.4, x_before.4), equals(x.4, x_after.4), equals(x.3, x_before.3), equals(x.3, x_after.3), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,
- af_tuple.1 AS step_reached,
- plus(af_tuple.1, 1) AS steps,
- af_tuple.2 AS breakdown,
- af_tuple.3 AS timings,
- af_tuple.5 AS steps_bitfield,
- aggregation_target AS aggregation_target
- FROM
- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,
- e.`$group_0` AS aggregation_target,
- e.uuid AS uuid,
- e.`$session_id` AS `$session_id`,
- e.`$window_id` AS `$window_id`,
- if(equals(e.event, 'step one'), 1, 0) AS step_0,
- if(equals(e.event, 'step two'), 1, 0) AS step_1,
- if(equals(e.event, 'step three'), 1, 0) AS step_2
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(groups.group_properties, 'name'), ''), 'null'), '^"|"$', '')), toTimeZone(groups._timestamp, 'UTC')), 1) AS properties___name,
- tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(groups.group_properties, 'slug'), ''), 'null'), '^"|"$', '')), toTimeZone(groups._timestamp, 'UTC')), 1) AS properties___slug,
- groups.group_type_index AS index,
- groups.group_key AS key
- FROM groups
- WHERE and(equals(groups.team_id, 99999), equals(index, 0))
- GROUP BY groups.group_type_index,
- groups.group_key) AS e__group_0 ON equals(e.`$group_0`, e__group_0.key)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '') AS properties___name
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('step one', 'step three', 'step two')), and(or(ifNull(ilike(toString(e__person.properties___email), '%g0%'), 0), ifNull(ilike(toString(e__person.properties___name), '%g0%'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'distinct_id'), ''), 'null'), '^"|"$', '')), '%g0%'), 0), ifNull(ilike(toString(e__group_0.properties___name), '%g0%'), 0), ifNull(ilike(toString(e__group_0.properties___slug), '%g0%'), 0)), ifNull(notEquals(nullIf(nullIf(e.`$group_0`, ''), 'null'), ''), 1)), and(notEquals(toString(aggregation_target), ''), isNotNull(aggregation_target))), or(equals(step_0, 1), equals(step_1, 1), equals(step_2, 1))))
- GROUP BY aggregation_target
- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
- WHERE bitTest(steps_bitfield, 0)
- ORDER BY aggregation_target ASC SETTINGS join_algorithm='auto') AS source
- ORDER BY source.actor_id ASC
- LIMIT 101
- OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto',
- readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
-# name: TestFunnelPerson.test_funnel_actors_with_groups_search[new_events_schema]
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT source.actor_id AS actor_id
- FROM
- (SELECT aggregation_target AS actor_id,
- actor_id AS key
- FROM
- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,
- [''] AS prop,
- arrayJoin(aggregate_funnel(3, 1209600, 'first_touch', 'ordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), equals(x.4, x_before.4), equals(x.4, x_after.4), equals(x.3, x_before.3), equals(x.3, x_after.3), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,
- af_tuple.1 AS step_reached,
- plus(af_tuple.1, 1) AS steps,
- af_tuple.2 AS breakdown,
- af_tuple.3 AS timings,
- af_tuple.5 AS steps_bitfield,
- aggregation_target AS aggregation_target
- FROM
- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,
- e.`$group_0` AS aggregation_target,
- e.uuid AS uuid,
- e.`$session_id` AS `$session_id`,
- e.`$window_id` AS `$window_id`,
- if(equals(e.event, 'step one'), 1, 0) AS step_0,
- if(equals(e.event, 'step two'), 1, 0) AS step_1,
- if(equals(e.event, 'step three'), 1, 0) AS step_2
- FROM events_json AS e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(groups.group_properties, 'name'), ''), 'null'), '^"|"$', '')), toTimeZone(groups._timestamp, 'UTC')), 1) AS properties___name,
- tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(groups.group_properties, 'slug'), ''), 'null'), '^"|"$', '')), toTimeZone(groups._timestamp, 'UTC')), 1) AS properties___slug,
- groups.group_type_index AS index,
- groups.group_key AS key
- FROM groups
- WHERE and(equals(groups.team_id, 99999), equals(index, 0))
- GROUP BY groups.group_type_index,
- groups.group_key) AS e__group_0 ON equals(e.`$group_0`, e__group_0.key)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '') AS properties___name
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('step one', 'step three', 'step two')), and(or(ifNull(ilike(toString(e__person.properties___email), '%g0%'), 0), ifNull(ilike(toString(e__person.properties___name), '%g0%'), 0), ifNull(ilike(toString(if(notEquals(toJSONString(e.properties.^distinct_id), '{}'), toJSONString(e.properties.^distinct_id), if(isNull(e.properties.distinct_id), NULL, if(startsWith(dynamicType(e.properties.distinct_id), 'DateTime'), replaceOne(toString(e.properties.distinct_id), ' ', 'T'), if(or(startsWith(dynamicType(e.properties.distinct_id), 'Array'), startsWith(dynamicType(e.properties.distinct_id), 'Map'), startsWith(dynamicType(e.properties.distinct_id), 'Tuple')), toJSONString(e.properties.distinct_id), toString(e.properties.distinct_id)))))), '%g0%'), 0), ifNull(ilike(toString(e__group_0.properties___name), '%g0%'), 0), ifNull(ilike(toString(e__group_0.properties___slug), '%g0%'), 0)), ifNull(notEquals(nullIf(nullIf(e.properties.`$group_0`, ''), 'null'), ''), 1)), and(notEquals(toString(aggregation_target), ''), isNotNull(aggregation_target))), or(equals(step_0, 1), equals(step_1, 1), equals(step_2, 1))))
- GROUP BY aggregation_target
- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
- WHERE bitTest(steps_bitfield, 0)
- ORDER BY aggregation_target ASC SETTINGS join_algorithm='auto') AS source
- ORDER BY source.actor_id ASC
- LIMIT 101
- OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto',
- readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
diff --git a/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_person.py b/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_person.py
deleted file mode 100644
index bb7f527d3544..000000000000
--- a/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_person.py
+++ /dev/null
@@ -1,341 +0,0 @@
-import json
-from typing import Any, cast
-
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_event,
- _create_person,
- snapshot_clickhouse_queries,
-)
-from unittest.mock import patch
-
-from django.core.cache import cache
-
-from rest_framework import status
-
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.group.util import create_group
-from posthog.models.instance_setting import get_instance_setting
-from posthog.test.persons import create_person, delete_person
-
-
-class TestFunnelPerson(ClickhouseTestMixin, APIBaseTest):
- def _create_sample_data(self, num, delete=False):
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="g0",
- properties={"slug": "g0", "name": "g0"},
- )
-
- for i in range(num):
- if delete:
- person = create_person(distinct_ids=[f"user_{i}"], team=self.team)
- else:
- _create_person(distinct_ids=[f"user_{i}"], team=self.team)
- _create_event(
- event="step one",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-01 00:00:00",
- properties={"$browser": "Chrome", "$group_0": "g0"},
- )
- _create_event(
- event="step two",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-03 00:00:00",
- properties={"$browser": "Chrome", "$group_0": "g0"},
- )
- _create_event(
- event="step three",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-05 00:00:00",
- properties={"$browser": "Chrome", "$group_0": "g0"},
- )
- if delete:
- delete_person(person)
-
- def test_basic_format(self):
- self._create_sample_data(5)
- request_data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "actions": json.dumps([]),
- "events": json.dumps(
- [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ]
- ),
- "properties": json.dumps([]),
- "funnel_window_days": 14,
- "funnel_step": 1,
- "filter_test_accounts": "false",
- "new_entity": json.dumps([]),
- "date_from": "2021-05-01",
- "date_to": "2021-05-10",
- }
-
- response = self.client.get("/api/person/funnel/", data=cast(Any, request_data))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- j = response.json()
- first_person = j["results"][0]["people"][0]
- self.assertEqual(5, len(j["results"][0]["people"]))
- self.assertTrue("id" in first_person and "name" in first_person and "distinct_ids" in first_person)
- self.assertEqual(5, j["results"][0]["count"])
-
- @snapshot_clickhouse_queries
- def test_funnel_actors_with_groups_search(self):
- self._create_sample_data(5)
-
- request_data = {
- "aggregation_group_type_index": 0,
- "search": "g0",
- "breakdown_attribution_type": "first_touch",
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "actions": json.dumps([]),
- "events": json.dumps(
- [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ]
- ),
- "properties": json.dumps([]),
- "funnel_window_days": 14,
- "funnel_step": 1,
- "filter_test_accounts": "false",
- "new_entity": json.dumps([]),
- "date_from": "2021-05-01",
- "date_to": "2021-05-10",
- }
-
- response = self.client.get("/api/person/funnel/", data=cast(Any, request_data))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- j = response.json()
- self.assertEqual(1, len(j["results"][0]["people"]))
- self.assertEqual(1, j["results"][0]["count"])
-
- def test_basic_pagination(self):
- cache.clear()
- self._create_sample_data(110)
- request_data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "actions": json.dumps([]),
- "events": json.dumps(
- [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ]
- ),
- "properties": json.dumps([]),
- "funnel_window_days": 14,
- "funnel_step": 1,
- "filter_test_accounts": "false",
- "new_entity": json.dumps([]),
- "date_from": "2021-05-01",
- "date_to": "2021-05-10",
- }
-
- response = self.client.get("/api/person/funnel/", data=cast(Any, request_data))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- j = response.json()
- people = j["results"][0]["people"]
- next = j["next"]
- self.assertEqual(100, len(people))
- self.assertNotEqual(None, next)
-
- response = self.client.get(next)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- j = response.json()
- people = j["results"][0]["people"]
- next = j["next"]
- self.assertEqual(10, len(people))
- self.assertEqual(None, j["next"])
-
- def test_breakdown_basic_pagination(self):
- cache.clear()
- self._create_sample_data(110)
- request_data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "actions": json.dumps([]),
- "events": json.dumps(
- [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ]
- ),
- "properties": json.dumps([]),
- "funnel_window_days": 14,
- "funnel_step": 1,
- "filter_test_accounts": "false",
- "new_entity": json.dumps([]),
- "date_from": "2021-05-01",
- "date_to": "2021-05-10",
- "breakdown_type": "event",
- "breakdown": "$browser",
- "funnel_step_breakdown": "Chrome",
- }
-
- response = self.client.get("/api/person/funnel/", data=cast(Any, request_data))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- j = response.json()
- people = j["results"][0]["people"]
- next = j["next"]
- self.assertEqual(100, len(people))
-
- response = self.client.get(next)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- j = response.json()
- people = j["results"][0]["people"]
- next = j["next"]
- self.assertEqual(10, len(people))
- self.assertEqual(None, j["next"])
-
- @patch("posthog.models.person.util.delete_person")
- def test_basic_pagination_with_deleted(self, delete_person_patch):
- if not get_instance_setting("PERSON_ON_EVENTS_ENABLED"):
- return
-
- cache.clear()
- self._create_sample_data(20, delete=True)
- request_data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "actions": json.dumps([]),
- "events": json.dumps(
- [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ]
- ),
- "properties": json.dumps([]),
- "funnel_window_days": 14,
- "funnel_step": 1,
- "filter_test_accounts": "false",
- "new_entity": json.dumps([]),
- "date_from": "2021-05-01",
- "date_to": "2021-05-10",
- "limit": 15,
- }
-
- response = self.client.get("/api/person/funnel/", data=cast(Any, request_data))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- j = response.json()
- people = j["results"][0]["people"]
- next = j["next"]
- missing_persons = j["missing_persons"]
- self.assertEqual(0, len(people))
- self.assertEqual(15, missing_persons)
- self.assertIsNotNone(next)
-
- response = self.client.get(next)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- j = response.json()
- people = j["results"][0]["people"]
- next = j["next"]
- missing_persons = j["missing_persons"]
- self.assertEqual(0, len(people))
- self.assertEqual(5, missing_persons)
- self.assertIsNone(next)
-
- def test_breakdowns(self):
- request_data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "actions": json.dumps([]),
- "properties": json.dumps([]),
- "funnel_step": 1,
- "filter_test_accounts": "false",
- "new_entity": json.dumps([]),
- "events": json.dumps(
- [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ]
- ),
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown": "$browser",
- "funnel_step_breakdown": "Chrome",
- }
-
- # event
- _create_person(distinct_ids=["person1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person1",
- properties={"key": "val", "$browser": "Chrome"},
- timestamp="2020-01-01T12:00:00Z",
- )
- _create_event(
- team=self.team,
- event="play movie",
- distinct_id="person1",
- properties={"key": "val", "$browser": "Chrome"},
- timestamp="2020-01-01T13:00:00Z",
- )
- _create_event(
- team=self.team,
- event="buy",
- distinct_id="person1",
- properties={"key": "val", "$browser": "Chrome"},
- timestamp="2020-01-01T15:00:00Z",
- )
-
- _create_person(distinct_ids=["person2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person2",
- properties={"key": "val", "$browser": "Safari"},
- timestamp="2020-01-02T14:00:00Z",
- )
- _create_event(
- team=self.team,
- event="play movie",
- distinct_id="person2",
- properties={"key": "val", "$browser": "Safari"},
- timestamp="2020-01-02T16:00:00Z",
- )
-
- _create_person(distinct_ids=["person3"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person3",
- properties={"key": "val", "$browser": "Safari"},
- timestamp="2020-01-02T14:00:00Z",
- )
-
- response = self.client.get("/api/person/funnel/", data=cast(Any, request_data))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- j = response.json()
-
- people = j["results"][0]["people"]
- self.assertEqual(1, len(people))
- self.assertEqual(None, j["next"])
-
- response = self.client.get(
- "/api/person/funnel/",
- data=cast(Any, {**request_data, "funnel_step_breakdown": "Safari"}),
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- j = response.json()
-
- people = j["results"][0]["people"]
- self.assertEqual(2, len(people))
- self.assertEqual(None, j["next"])
diff --git a/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_trends_person.py b/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_trends_person.py
deleted file mode 100644
index 91d1fd1dba95..000000000000
--- a/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_trends_person.py
+++ /dev/null
@@ -1,245 +0,0 @@
-import json
-from typing import Any, cast
-
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
-
-from rest_framework import status
-
-from posthog.constants import INSIGHT_FUNNELS, FunnelOrderType, FunnelVizType
-
-
-class TestFunnelTrendsPerson(ClickhouseTestMixin, APIBaseTest):
- def test_basic_format(self):
- user_a = _create_person(distinct_ids=["user a"], team=self.team)
-
- _create_event(
- event="step one",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-07 19:00:00",
- )
-
- common_request_data = {
- "insight": INSIGHT_FUNNELS,
- "funnel_viz_type": FunnelVizType.TRENDS,
- "interval": "day",
- "date_from": "2021-06-07",
- "date_to": "2021-06-13 23:59:59",
- "funnel_window_days": 7,
- "events": json.dumps(
- [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ]
- ),
- "properties": json.dumps([]),
- "new_entity": json.dumps([]),
- }
-
- # 1 user who dropped off starting 2021-06-07
- response_1 = self.client.get(
- "/api/person/funnel/",
- data=cast(Any, {**common_request_data, "entrance_period_start": "2021-06-07", "drop_off": True}),
- )
- response_1_data = response_1.json()
-
- self.assertEqual(response_1.status_code, status.HTTP_200_OK)
- self.assertEqual(
- [person["id"] for person in response_1_data["results"][0]["people"]],
- [str(user_a.uuid)],
- )
-
- # No users converted 2021-06-07
- response_2 = self.client.get(
- "/api/person/funnel/",
- data=cast(Any, {**common_request_data, "entrance_period_start": "2021-06-07 00:00", "drop_off": False}),
- )
- response_2_data = response_2.json()
-
- self.assertEqual(response_2.status_code, status.HTTP_200_OK)
- self.assertEqual([person["id"] for person in response_2_data["results"][0]["people"]], [])
-
- # No users dropped off starting 2021-06-08
- response_3 = self.client.get(
- "/api/person/funnel/",
- data=cast(Any, {**common_request_data, "entrance_period_start": "2021-06-08", "drop_off": True}),
- )
- response_3_data = response_3.json()
-
- self.assertEqual(response_3.status_code, status.HTTP_200_OK)
- self.assertEqual([person["id"] for person in response_3_data["results"][0]["people"]], [])
-
- def test_strict_order(self):
- user_a = _create_person(distinct_ids=["user a"], team=self.team)
- user_b = _create_person(distinct_ids=["user b"], team=self.team)
-
- _create_event(
- event="step one",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-07 19:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-07 19:00:01",
- )
- _create_event(
- event="step one",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-07 19:00:02",
- )
- _create_event(
- event="step three",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-07 19:00:03",
- )
-
- _create_event(
- event="step one",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-07 19:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-07 19:00:01",
- )
- _create_event(
- event="step three",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-07 19:00:03",
- )
-
- common_request_data = {
- "insight": INSIGHT_FUNNELS,
- "funnel_viz_type": FunnelVizType.TRENDS,
- "interval": "day",
- "date_from": "2021-06-07",
- "date_to": "2021-06-13 23:59:59",
- "funnel_window_days": 7,
- "funnel_order_type": FunnelOrderType.STRICT,
- "events": json.dumps(
- [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ]
- ),
- "properties": json.dumps([]),
- "new_entity": json.dumps([]),
- }
-
- # 1 user who dropped off
- response_1 = self.client.get(
- "/api/person/funnel/",
- data=cast(Any, {**common_request_data, "entrance_period_start": "2021-06-07", "drop_off": True}),
- )
- response_1_data = response_1.json()
-
- self.assertEqual(response_1.status_code, status.HTTP_200_OK)
- self.assertEqual(
- [person["id"] for person in response_1_data["results"][0]["people"]],
- [str(user_a.uuid)],
- )
-
- # 1 user who successfully converted
- response_1 = self.client.get(
- "/api/person/funnel/",
- data=cast(Any, {**common_request_data, "entrance_period_start": "2021-06-07", "drop_off": False}),
- )
- response_1_data = response_1.json()
-
- self.assertEqual(response_1.status_code, status.HTTP_200_OK)
- self.assertEqual(
- [person["id"] for person in response_1_data["results"][0]["people"]],
- [str(user_b.uuid)],
- )
-
- def test_unordered(self):
- user_a = _create_person(distinct_ids=["user a"], team=self.team)
- user_b = _create_person(distinct_ids=["user b"], team=self.team)
-
- _create_event(
- event="step one",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-07 19:00:00",
- )
- _create_event(
- event="step three",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-07 19:00:03",
- )
-
- _create_event(
- event="step one",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-07 19:00:00",
- )
- _create_event(
- event="step three",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-07 19:00:01",
- )
- _create_event(
- event="step two",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-07 19:00:02",
- )
-
- common_request_data = {
- "insight": INSIGHT_FUNNELS,
- "funnel_viz_type": FunnelVizType.TRENDS,
- "interval": "day",
- "date_from": "2021-06-07",
- "date_to": "2021-06-13 23:59:59",
- "funnel_window_days": 7,
- "funnel_order_type": FunnelOrderType.UNORDERED,
- "events": json.dumps(
- [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ]
- ),
- "properties": json.dumps([]),
- "new_entity": json.dumps([]),
- }
-
- # 1 user who dropped off
- response_1 = self.client.get(
- "/api/person/funnel/",
- data=cast(Any, {**common_request_data, "entrance_period_start": "2021-06-07", "drop_off": True}),
- )
- response_1_data = response_1.json()
-
- self.assertEqual(response_1.status_code, status.HTTP_200_OK)
- self.assertEqual(
- [person["id"] for person in response_1_data["results"][0]["people"]],
- [str(user_a.uuid)],
- )
-
- # 1 user who successfully converted
- response_1 = self.client.get(
- "/api/person/funnel/",
- data=cast(Any, {**common_request_data, "entrance_period_start": "2021-06-07", "drop_off": False}),
- )
- response_1_data = response_1.json()
-
- self.assertEqual(response_1.status_code, status.HTTP_200_OK)
- self.assertEqual(
- [person["id"] for person in response_1_data["results"][0]["people"]],
- [str(user_b.uuid)],
- )
diff --git a/posthog/api/person.py b/posthog/api/person.py
index afa5c15c5af4..16a0da791bcb 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -2,8 +2,8 @@ import json
import uuid
import builtins
import dataclasses
-from datetime import UTC, datetime, timedelta
-from typing import Any, List, Optional, TypeVar, Union, cast # noqa: UP035
+from datetime import UTC, datetime
+from typing import Any, Optional, Union, cast # noqa: UP035
import structlog
from drf_spectacular.types import OpenApiTypes
@@ -26,7 +26,14 @@ from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework_csv import renderers as csvrenderers
-from posthog.schema import ActorsQuery, ProductKey
+from posthog.schema import (
+ ActorsQuery,
+ HogQLQueryModifiers,
+ InlineCohortCalculation,
+ InsightActorsQuery,
+ LifecycleQuery,
+ ProductKey,
+)
from posthog.hogql.constants import CSV_EXPORT_LIMIT
@@ -34,22 +41,20 @@ from posthog.api.capture import CaptureInternalError, capture_internal
from posthog.api.documentation import PersonPropertiesSerializer
from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATION
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.utils import action, format_paginated_url, get_target_entity
+from posthog.api.utils import action, format_paginated_url
from posthog.auth import PersonalAPIKeyAuthentication
from posthog.clickhouse.query_tagging import Feature, tag_queries
-from posthog.constants import INSIGHT_FUNNELS, LIMIT, OFFSET, FunnelVizType
-from posthog.decorators import cached_by_filters
+from posthog.constants import LIMIT, OFFSET
from posthog.event_usage import get_request_analytics_properties
from posthog.helpers.impersonation import is_impersonated
+from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query
from posthog.metrics import LABEL_TEAM_ID
from posthog.models import Filter, Person, Team, User
from posthog.models.activity_logging.activity_log import Change, Detail, load_activity, log_activity
from posthog.models.activity_logging.activity_page import activity_page_response
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.filters.lifecycle_filter import LifecycleFilter
-from posthog.models.filters.path_filter import PathFilter
from posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilter
-from posthog.models.filters.retention_filter import RetentionFilter
from posthog.models.person.bulk_delete import (
delete_persons_profile,
queue_person_event_deletion,
@@ -65,7 +70,7 @@ from posthog.models.person.util import (
get_persons_mapped_by_distinct_id,
)
from posthog.personhog_client.caller_tag import personhog_caller_tag
-from posthog.queries.actor_base_query import get_serialized_people
+from posthog.queries.actor_base_query import get_groups, get_serialized_people
from posthog.queries.properties_timeline import PropertiesTimeline
from posthog.rate_limit import ClickHouseBurstRateThrottle, PersonalApiKeyRateThrottle, UserOrEmailRateThrottle
from posthog.renderers import SafeJSONRenderer
@@ -79,7 +84,6 @@ from posthog.utils import (
from products.cohorts.backend.models.cohort import Cohort
from products.cohorts.backend.models.util import get_all_cohort_ids_by_person_uuid
-from products.product_analytics.backend.api.insight import capture_legacy_api_call
from products.workflows.backend.api.message_assets import (
MessageAssetSerializer,
PersonMessageAssetsRequestSerializer,
@@ -1192,274 +1196,6 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
# PRAGMA: Methods for getting Persons via clickhouse queries
- def _respond_with_cached_results(
- self, results_package: dict[str, tuple[builtins.list, Optional[str], Optional[str], int]]
- ): # noqa: UP006
- if not results_package:
- return response.Response(data=[])
-
- actors, next_url, initial_url, missing_persons = results_package["result"]
-
- return response.Response(
- data={
- "results": [{"people": actors, "count": len(actors)}],
- "next": next_url,
- "initial": initial_url,
- "missing_persons": missing_persons,
- "is_cached": results_package.get("is_cached"),
- "last_refresh": results_package.get("last_refresh"),
- }
- )
-
- def _legacy_session_ids_with_recordings(self, session_ids: set[str], filter: Filter) -> set[str]:
- """Filter session ids to those with a (non-deleted) recording, mirroring the legacy actor endpoint.
- Unlike the modern RecordingsHelper this does not apply a retention/expiry window, preserving the
- long-standing response shape of these public endpoints.
- """
- if not session_ids:
- return set()
-
- from posthog.clickhouse.client import sync_execute # noqa: PLC0415
-
- query = """
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = %(team_id)s AND session_id IN %(session_ids)s
- """
- params: dict[str, Any] = {"team_id": self.team.pk, "session_ids": sorted(session_ids)}
- if filter.date_from:
- query += " AND min_first_timestamp >= %(date_from)s"
- params["date_from"] = filter.date_from - timedelta(days=1)
- if filter.date_to:
- query += " AND max_last_timestamp <= %(date_to)s"
- params["date_to"] = filter.date_to + timedelta(days=1)
- query += " GROUP BY session_id HAVING max(is_deleted) = 0"
-
- return {row[0] for row in sync_execute(query, params)}
-
- @staticmethod
- def _legacy_breakdown_value(filter: Filter) -> Optional[Union[str, int]]:
- """Translate the legacy `breakdown_value` request param into the value the HogQL trends actors path
- expects: an empty string means the null/none bucket, a cohort breakdown value is an int cohort id.
- """
- from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL # noqa: PLC0415
-
- value = filter.breakdown_value
- if value is None:
- return None
- if filter.breakdown_type == "cohort":
- return value if value == "all" else int(value)
- if value == "":
- return BREAKDOWN_NULL_STRING_LABEL
- return value
-
- def _run_legacy_actors_query(
- self,
- source: Any,
- filter: Filter,
- *,
- aggregation_group_type_index: Optional[int],
- include_value: bool,
- include_recordings: bool,
- ) -> tuple[builtins.list, int]:
- """Run an ActorsQuery (the HogQL actor path used by the modern /query route) and reshape the
- results into the legacy SerializedPerson/SerializedGroup envelope these endpoints have always
- returned. `source` is an InsightActorsQuery or FunnelsActorsQuery.
- """
- from posthog.schema import HogQLQueryModifiers, InlineCohortCalculation # noqa: PLC0415
-
- from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner # noqa: PLC0415
- from posthog.queries.actor_base_query import get_groups # noqa: PLC0415
-
- # Raw id-only select (plus value/recordings columns) — we hydrate actors ourselves below, matching
- # the legacy SerializedPerson shape rather than the ActorsQuery strategy dict.
- select: list[str] = ["actor_id"]
- if include_value:
- select.append("event_count")
- if include_recordings:
- select.append("matched_recordings")
-
- actors_query = ActorsQuery(
- source=source,
- select=select,
- limit=filter.limit,
- offset=filter.offset,
- )
- # Inline cohort definitions instead of reading precomputed membership — the legacy actor queries
- # expanded cohorts inline, so a cohort breakdown/filter works without a prior cohort calculation.
- # The modifiers must live on the inner insight query: ActorsQueryRunner inherits its modifiers from
- # the source query runner, which derives them from `source.source.modifiers`.
- source.source.modifiers = (source.source.modifiers or HogQLQueryModifiers()).model_copy(
- update={"inlineCohortCalculation": InlineCohortCalculation.ALWAYS}
- )
- runner = ActorsQueryRunner(team=self.team, query=actors_query)
- results = list(runner.calculate().results)
- raw_count = len(results)
-
- actor_ids = [str(row[0]) for row in results]
- value_per_actor_id: Optional[dict[str, float]] = (
- {str(row[0]): row[1] for row in results} if include_value else None
- )
-
- serialized_actors: list[Any]
- if aggregation_group_type_index is not None:
- _, serialized_actors = get_groups(self.team.pk, aggregation_group_type_index, actor_ids, value_per_actor_id)
- else:
- serialized_actors = get_serialized_people(self.team, actor_ids, value_per_actor_id)
-
- if include_recordings:
- recordings_column_index = select.index("matched_recordings")
- all_session_ids = {event[2] for row in results for event in row[recordings_column_index] if event[2]}
- valid_session_ids = self._legacy_session_ids_with_recordings(all_session_ids, filter)
- recordings_by_actor_id: dict[str, builtins.list] = {}
- for row in results:
- events_by_session: dict[str, builtins.list] = {}
- for event in row[recordings_column_index]:
- session_id = event[2]
- if session_id and session_id in valid_session_ids:
- events_by_session.setdefault(session_id, []).append(
- {"timestamp": event[0], "uuid": event[1], "window_id": event[3]}
- )
- recordings_by_actor_id[str(row[0])] = [
- {"session_id": session_id, "events": events} for session_id, events in events_by_session.items()
- ]
- for actor in serialized_actors:
- actor["matched_recordings"] = recordings_by_actor_id.get(str(actor["id"]), [])
-
- if include_value:
- # get_serialized_people / get_groups fetch actors out of order, so restore the
- # descending-by-value ordering the legacy endpoint guaranteed.
- serialized_actors.sort(key=lambda actor: cast(float, actor["value_at_data_point"]), reverse=True)
-
- return serialized_actors, raw_count
-
- @action(methods=["GET", "POST"], detail=False)
- def funnel(self, request: request.Request, **kwargs) -> response.Response:
- capture_legacy_api_call(request, self.team)
-
- if request.user.is_anonymous or not self.team:
- return response.Response(data=[])
-
- return self._respond_with_cached_results(self.calculate_funnel_persons(request))
-
- @cached_by_filters
- def calculate_funnel_persons(
- self, request: request.Request
- ) -> dict[str, tuple[List, Optional[str], Optional[str], int]]: # noqa: UP006
- from posthog.schema import FunnelsActorsQuery, FunnelsQuery # noqa: PLC0415
-
- from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query # noqa: PLC0415
-
- filter = Filter(request=request, data={"insight": INSIGHT_FUNNELS}, team=self.team)
- filter = prepare_actor_query_filter(filter)
-
- funnels_query = cast(FunnelsQuery, filter_to_query(filter.to_dict()))
- if filter.funnel_viz_type == FunnelVizType.TRENDS:
- # Funnel-trends actors are addressed by an entrance period + converted/dropped-off flag,
- # not by a step index.
- source = FunnelsActorsQuery(
- source=funnels_query,
- funnelTrendsDropOff=bool(filter.drop_off),
- funnelTrendsEntrancePeriodStart=request.GET.get("entrance_period_start"),
- funnelStepBreakdown=filter.funnel_step_breakdown,
- includeRecordings=filter.include_recordings,
- )
- else:
- funnel_step = filter.funnel_step
- if funnel_step is None and filter.funnel_custom_steps:
- funnel_step = filter.funnel_custom_steps[0]
- source = FunnelsActorsQuery(
- source=funnels_query,
- funnelStep=funnel_step,
- funnelStepBreakdown=filter.funnel_step_breakdown,
- includeRecordings=filter.include_recordings,
- )
-
- serialized_actors, raw_count = self._run_legacy_actors_query(
- source,
- filter,
- aggregation_group_type_index=funnels_query.aggregation_group_type_index,
- include_value=False,
- include_recordings=bool(filter.include_recordings),
- )
- initial_url = format_query_params_absolute_url(request, 0)
- next_url = paginated_result(request, raw_count, filter.offset, filter.limit)
-
- # cached_function expects a dict with the key result
- return {
- "result": (
- serialized_actors,
- next_url,
- initial_url,
- raw_count - len(serialized_actors),
- )
- }
-
- @action(methods=["GET"], detail=False)
- def trends(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:
- capture_legacy_api_call(request, self.team)
-
- if request.user.is_anonymous or not self.team:
- return response.Response(data=[])
-
- return self._respond_with_cached_results(self.calculate_trends_persons(request))
-
- @cached_by_filters
- def calculate_trends_persons(
- self, request: request.Request
- ) -> dict[str, tuple[List, Optional[str], Optional[str], int]]: # noqa: UP006
- from posthog.schema import ChartDisplayType, InsightActorsQuery, TrendsFilter, TrendsQuery # noqa: PLC0415
-
- from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query # noqa: PLC0415
-
- filter = Filter(request=request, team=self.team)
- filter = prepare_actor_query_filter(filter)
- entity = get_target_entity(filter)
-
- # The trends person endpoint identifies its target series via the entity params (entity_id/type),
- # not an events/actions list, so inject the resolved entity as the single series before converting.
- filter_dict = {**filter.to_dict(), "insight": "TRENDS"}
- entity_dict = {**entity.to_dict(), "order": 0}
- if entity.type == "actions":
- filter_dict["actions"] = [entity_dict]
- filter_dict["events"] = []
- else:
- filter_dict["events"] = [entity_dict]
- filter_dict["actions"] = []
-
- trends_query = cast(TrendsQuery, filter_to_query(filter_dict))
- # The legacy endpoint returns every actor that performed the series anywhere in the filter's date
- # range (no per-interval `day`). A total-value display gives exactly that aggregation, so the actors
- # builder doesn't require a `day`.
- trends_query.trendsFilter = trends_query.trendsFilter or TrendsFilter()
- trends_query.trendsFilter.display = ChartDisplayType.ACTIONS_BAR_VALUE
- source = InsightActorsQuery(
- source=trends_query,
- series=0,
- breakdown=self._legacy_breakdown_value(filter),
- includeRecordings=filter.include_recordings,
- )
-
- serialized_actors, raw_count = self._run_legacy_actors_query(
- source,
- filter,
- aggregation_group_type_index=entity.math_group_type_index,
- include_value=True,
- include_recordings=bool(filter.include_recordings),
- )
- next_url = paginated_result(request, raw_count, filter.offset, filter.limit)
- initial_url = format_query_params_absolute_url(request, 0)
-
- # cached_function expects a dict with the key result
- return {
- "result": (
- serialized_actors,
- next_url,
- initial_url,
- raw_count - len(serialized_actors),
- )
- }
-
@action(methods=["GET"], detail=True)
def properties_timeline(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:
if request.user.is_anonymous or not self.team:
@@ -1542,9 +1278,9 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
status=400,
)
- from posthog.schema import InsightActorsQuery, LifecycleQuery # noqa: PLC0415
-
- from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query # noqa: PLC0415
+ from posthog.hogql_queries.actors_query_runner import ( # noqa: PLC0415 — breaks import cycle (actors_query_runner imports from this module)
+ ActorsQueryRunner,
+ )
filter = LifecycleFilter(request=request, data=request.GET.dict(), team=self.team)
filter = prepare_actor_query_filter(filter)
@@ -1552,15 +1288,24 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
lifecycle_query = cast(LifecycleQuery, filter_to_query({**filter.to_dict(), "insight": "LIFECYCLE"}))
source = InsightActorsQuery(source=lifecycle_query, day=target_date, status=lifecycle_type)
+ # Select actor ids only and hydrate them ourselves to keep the legacy response shape.
+ actors_query = ActorsQuery(source=source, select=["actor_id"], limit=filter.limit, offset=filter.offset)
+ # Expand cohorts inline so cohort filters work without a precomputed cohort. The modifier
+ # goes on the inner query because ActorsQueryRunner inherits modifiers from its source.
+ source.source.modifiers = (source.source.modifiers or HogQLQueryModifiers()).model_copy(
+ update={"inlineCohortCalculation": InlineCohortCalculation.ALWAYS}
+ )
with personhog_caller_tag("persons/lifecycle"):
- people, raw_count = self._run_legacy_actors_query(
- source,
- filter,
- aggregation_group_type_index=lifecycle_query.aggregation_group_type_index,
- include_value=False,
- include_recordings=False,
- )
- next_url = paginated_result(request, raw_count, filter.offset, filter.limit)
+ results = list(ActorsQueryRunner(team=self.team, query=actors_query).calculate().results)
+ actor_ids = [str(row[0]) for row in results]
+
+ people: list[Any]
+ if lifecycle_query.aggregation_group_type_index is not None:
+ _, people = get_groups(self.team.pk, lifecycle_query.aggregation_group_type_index, actor_ids, None)
+ else:
+ people = get_serialized_people(self.team, actor_ids, None)
+
+ next_url = format_paginated_url(request, filter.offset, filter.limit) if len(results) >= filter.limit else None
return response.Response({"results": [{"people": people, "count": len(people)}], "next": next_url})
@extend_schema(
@@ -1833,19 +1578,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
-def paginated_result(
- request: request.Request,
- count: int,
- offset: int = 0,
- limit: int = DEFAULT_PAGE_LIMIT,
-) -> Optional[str]:
- return format_paginated_url(request, offset, limit) if count >= limit else None
-
-
-T = TypeVar("T", Filter, PathFilter, RetentionFilter, LifecycleFilter)
-
-
-def prepare_actor_query_filter(filter: T) -> T:
+def prepare_actor_query_filter(filter: LifecycleFilter) -> LifecycleFilter:
if not filter.limit:
filter = filter.shallow_clone({LIMIT: DEFAULT_PAGE_LIMIT})
diff --git a/posthog/api/test/test_persons_trends.py b/posthog/api/test/test_persons_trends.py
deleted file mode 100644
index f44c743781ee..000000000000
--- a/posthog/api/test/test_persons_trends.py
+++ /dev/null
@@ -1,1065 +0,0 @@
-import json
-from datetime import datetime
-
-from freezegun import freeze_time
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_action,
- _create_event,
- _create_person,
- flush_persons_and_events,
- snapshot_clickhouse_queries,
-)
-
-from posthog.constants import ENTITY_ID, ENTITY_MATH, ENTITY_TYPE, TRENDS_CUMULATIVE
-from posthog.models import Organization
-from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
-
-from products.cohorts.backend.models.cohort import Cohort
-
-
-def _create_cohort(**kwargs):
- team = kwargs.pop("team")
- name = kwargs.pop("name")
- groups = kwargs.pop("groups")
- cohort = Cohort.objects.create(team=team, name=name, groups=groups)
- return cohort
-
-
-class TestPersonTrends(ClickhouseTestMixin, APIBaseTest):
- def _create_events(self, use_time=False):
- _create_action(team=self.team, name="no events")
-
- sign_up_action = _create_action(team=self.team, name="sign up")
-
- person = _create_person(team_id=self.team.pk, distinct_ids=["blabla", "anonymous_id"])
- secondTeam = Organization.objects.bootstrap(None, team_fields={"api_token": "token456"})[2]
-
- freeze_without_time = ["2019-12-24", "2020-01-01", "2020-01-02"]
- freeze_with_time = [
- "2019-12-24 03:45:34",
- "2020-01-01 00:06:34",
- "2020-01-02 16:34:34",
- ]
-
- freeze_args = freeze_without_time
- if use_time:
- freeze_args = freeze_with_time
-
- with freeze_time(freeze_args[0]):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value"},
- )
-
- with freeze_time(freeze_args[1]):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value"},
- )
- _create_event(team=self.team, event="sign up", distinct_id="anonymous_id")
- _create_event(team=self.team, event="sign up", distinct_id="blabla")
- with freeze_time(freeze_args[2]):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$some_property": "other_value",
- "$some_numerical_prop": 80,
- },
- )
- _create_event(team=self.team, event="no events", distinct_id="blabla")
-
- # second team should have no effect
- _create_event(
- team=secondTeam,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "other_value"},
- )
-
- flush_persons_and_events()
- return sign_up_action, person
-
- def test_people_cumulative(self):
- with freeze_time("2020-01-01 00:06:34"):
- for i in range(20):
- _create_person(team_id=self.team.pk, distinct_ids=[f"blabla_{i}"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id=f"blabla_{i}",
- properties={"$some_property": "value"},
- )
-
- with freeze_time("2020-01-05 00:06:34"):
- for i in range(20, 40):
- _create_person(team_id=self.team.pk, distinct_ids=[f"blabla_{i}"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id=f"blabla_{i}",
- properties={"$some_property": "value"},
- )
-
- with freeze_time("2020-01-15 00:06:34"):
- for i in range(40, 80):
- _create_person(team_id=self.team.pk, distinct_ids=[f"blabla_{i}"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id=f"blabla_{i}",
- properties={"$some_property": "value"},
- )
-
- event_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-01",
- "date_to": "2020-01-31",
- "interval": "day",
- ENTITY_TYPE: "events",
- ENTITY_ID: "sign up",
- "display": "ActionsLineGraphCumulative",
- },
- ).json()
- self.assertEqual(event_response["results"][0]["count"], 80)
-
- with freeze_time("2020-01-31 00:06:34"):
- event_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "-30d",
- "date_to": "2020-01-31",
- "interval": "day",
- ENTITY_TYPE: "events",
- ENTITY_ID: "sign up",
- "display": "ActionsLineGraphCumulative",
- },
- ).json()
- self.assertEqual(event_response["results"][0]["count"], 80)
-
- def _create_breakdown_events(self):
- freeze_without_time = ["2020-01-02"]
-
- _create_action(team=self.team, name="sign up")
-
- with freeze_time(freeze_without_time[0]):
- for i in range(25):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": i},
- )
-
- flush_persons_and_events()
-
- def test_people_endpoint_paginated(self):
- for index in range(0, 150):
- _create_person(team_id=self.team.pk, distinct_ids=["person" + str(index)])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person" + str(index),
- timestamp="2020-01-04T12:00:00Z",
- )
-
- event_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-04",
- "date_to": "2020-01-04",
- ENTITY_TYPE: "events",
- ENTITY_ID: "sign up",
- },
- ).json()
-
- self.assertEqual(len(event_response["results"][0]["people"]), 100)
- event_response_next = self.client.get(event_response["next"]).json()
- self.assertEqual(len(event_response_next["results"][0]["people"]), 50)
-
- def _create_people_interval_events(self):
- person1 = _create_person(team_id=self.team.pk, distinct_ids=["person1"])
- person2 = _create_person(team_id=self.team.pk, distinct_ids=["person2"])
- person3 = _create_person(team_id=self.team.pk, distinct_ids=["person3"])
- person4 = _create_person(team_id=self.team.pk, distinct_ids=["person4"])
- person5 = _create_person(team_id=self.team.pk, distinct_ids=["person5"])
- person6 = _create_person(team_id=self.team.pk, distinct_ids=["person6"])
- person7 = _create_person(team_id=self.team.pk, distinct_ids=["person7"])
-
- # solo
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person1",
- timestamp="2020-01-04T14:10:00Z",
- )
- # group by hour
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person2",
- timestamp="2020-01-04T16:30:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person3",
- timestamp="2020-01-04T16:50:00Z",
- )
- # group by min
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person4",
- timestamp="2020-01-04T19:20:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person5",
- timestamp="2020-01-04T19:20:00Z",
- )
- # group by week and month
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person6",
- timestamp="2019-11-05T16:30:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person7",
- timestamp="2019-11-07T16:50:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person1",
- timestamp="2019-11-27T16:50:00Z",
- )
-
- flush_persons_and_events()
- return person1, person2, person3, person4, person5, person6, person7
-
- def test_hour_interval(self):
- sign_up_action, person = self._create_events()
-
- (
- person1,
- person2,
- person3,
- person4,
- person5,
- person6,
- person7,
- ) = self._create_people_interval_events()
-
- _create_person(team_id=self.team.pk, distinct_ids=["outside_range"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="outside_range",
- timestamp="2020-01-04T13:50:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="outside_range",
- timestamp="2020-01-04T15:50:00Z",
- )
- # check solo hour
- action_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "interval": "hour",
- "date_from": "2020-01-04 14:00:00",
- "date_to": "2020-01-04 14:59:59",
- ENTITY_TYPE: "actions",
- ENTITY_ID: sign_up_action.id,
- },
- ).json()
- event_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "interval": "hour",
- "date_from": "2020-01-04 14:00:00",
- "date_to": "2020-01-04 14:59:59",
- ENTITY_TYPE: "events",
- ENTITY_ID: "sign up",
- },
- ).json()
- self.assertEqual(str(action_response["results"][0]["people"][0]["id"]), str(person1.uuid))
- self.assertEqual(len(action_response["results"][0]["people"]), 1)
- self.assertEntityResponseEqual(action_response["results"], event_response["results"], remove=[])
-
- # check grouped hour
- hour_grouped_action_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "interval": "hour",
- "date_from": "2020-01-04 16:00:00",
- "date_to": "2020-01-04 16:59:59",
- ENTITY_TYPE: "actions",
- ENTITY_ID: sign_up_action.id,
- },
- ).json()
- hour_grouped_grevent_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "interval": "hour",
- "date_from": "2020-01-04 16:00:00",
- "date_to": "2020-01-04 16:59:59",
- ENTITY_TYPE: "events",
- ENTITY_ID: "sign up",
- },
- ).json()
- all_people_ids = [str(person["id"]) for person in hour_grouped_action_response["results"][0]["people"]]
- self.assertListEqual(sorted(all_people_ids), sorted([str(person2.uuid), str(person3.uuid)]))
- self.assertEqual(len(all_people_ids), 2)
- self.assertEntityResponseEqual(
- hour_grouped_action_response["results"],
- hour_grouped_grevent_response["results"],
- remove=[],
- )
-
- def test_day_interval(self):
- sign_up_action, person = self._create_events()
- person1 = _create_person(team_id=self.team.pk, distinct_ids=["person1"])
- _create_person(team_id=self.team.pk, distinct_ids=["person2"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person1",
- timestamp="2020-01-04T12:00:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person2",
- timestamp="2020-01-05T12:00:00Z",
- )
- _create_person(team_id=self.team.pk, distinct_ids=["outside_range"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="outside_range",
- timestamp="2020-01-03T13:50:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="outside_range",
- timestamp="2020-01-05T15:50:00Z",
- )
-
- # test people
- action_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-04",
- "date_to": "2020-01-04 23:59:59",
- ENTITY_TYPE: "actions",
- "interval": "day",
- ENTITY_ID: sign_up_action.id,
- },
- ).json()
- event_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-04",
- "date_to": "2020-01-04 23:59:59",
- ENTITY_TYPE: "events",
- ENTITY_ID: "sign up",
- "interval": "day",
- },
- ).json()
-
- self.assertEqual(len(action_response["results"][0]["people"]), 1)
- self.assertEqual(str(action_response["results"][0]["people"][0]["id"]), str(person1.uuid))
- self.assertEntityResponseEqual(action_response["results"], event_response["results"], remove=[])
-
- def test_day_interval_cumulative(self):
- sign_up_action, person = self._create_events()
- person1 = _create_person(team_id=self.team.pk, distinct_ids=["person1"])
- person2 = _create_person(team_id=self.team.pk, distinct_ids=["person2"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person1",
- timestamp="2020-01-03T12:00:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person2",
- timestamp="2020-01-04T20:00:00Z",
- )
- _create_person(team_id=self.team.pk, distinct_ids=["outside_range"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="outside_range",
- timestamp="2020-01-02T13:50:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="outside_range",
- timestamp="2020-01-05T15:50:00Z",
- )
-
- # test people
- action_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-03",
- "date_to": "2020-01-04 23:59:59",
- ENTITY_TYPE: "actions",
- "interval": "day",
- ENTITY_ID: sign_up_action.id,
- "display": TRENDS_CUMULATIVE,
- },
- ).json()
- event_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-03",
- "date_to": "2020-01-04 23:59:59",
- ENTITY_TYPE: "events",
- ENTITY_ID: "sign up",
- "interval": "day",
- "display": TRENDS_CUMULATIVE,
- },
- ).json()
- self.assertEqual(len(action_response["results"][0]["people"]), 2)
- self.assertEqual(
- sorted(p["id"] for p in action_response["results"][0]["people"]),
- sorted([str(person1.uuid), str(person2.uuid)]),
- )
- self.assertEntityResponseEqual(action_response["results"], event_response["results"], remove=[])
-
- def test_week_interval(self):
- sign_up_action, person = self._create_events()
-
- (
- person1,
- person2,
- person3,
- person4,
- person5,
- person6,
- person7,
- ) = self._create_people_interval_events()
-
- _create_person(team_id=self.team.pk, distinct_ids=["outside_range"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="outside_range",
- timestamp="2019-10-26T13:50:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="outside_range",
- timestamp="2020-11-11T15:50:00Z",
- )
- # check grouped week
- week_grouped_action_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "interval": "week",
- "date_from": "2019-11-01",
- "date_to": "2019-11-07",
- ENTITY_TYPE: "actions",
- ENTITY_ID: sign_up_action.id,
- },
- ).json()
- week_grouped_grevent_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "interval": "week",
- "date_from": "2019-11-01",
- "date_to": "2019-11-07",
- ENTITY_TYPE: "events",
- ENTITY_ID: "sign up",
- },
- ).json()
-
- self.maxDiff = None
- all_people_ids = [str(person["id"]) for person in week_grouped_action_response["results"][0]["people"]]
- self.assertEqual(len(all_people_ids), 2)
- self.assertListEqual(sorted(all_people_ids), sorted([str(person6.uuid), str(person7.uuid)]))
-
- self.assertEntityResponseEqual(
- week_grouped_action_response["results"],
- week_grouped_grevent_response["results"],
- remove=[],
- )
-
- def test_month_interval(self):
- sign_up_action, person = self._create_events()
-
- (
- person1,
- person2,
- person3,
- person4,
- person5,
- person6,
- person7,
- ) = self._create_people_interval_events()
-
- _create_person(team_id=self.team.pk, distinct_ids=["outside_range"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="outside_range",
- timestamp="2019-12-01T13:50:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="outside_range",
- timestamp="2020-10-10T15:50:00Z",
- )
- # check grouped month
- month_group_action_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "interval": "month",
- "date_from": "2019-11-01",
- "date_to": "2019-11-30",
- ENTITY_TYPE: "actions",
- ENTITY_ID: sign_up_action.id,
- },
- ).json()
- month_group_grevent_response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "interval": "month",
- "date_from": "2019-11-01",
- "date_to": "2019-11-30",
- ENTITY_TYPE: "events",
- ENTITY_ID: "sign up",
- },
- ).json()
-
- all_people_ids = [str(person["id"]) for person in month_group_action_response["results"][0]["people"]]
- self.assertEqual(len(all_people_ids), 3)
- self.assertListEqual(
- sorted(all_people_ids),
- sorted([str(person6.uuid), str(person7.uuid), str(person1.uuid)]),
- )
-
- self.assertEntityResponseEqual(
- month_group_action_response["results"],
- month_group_grevent_response["results"],
- remove=[],
- )
-
- def _create_multiple_people(self):
- person1 = _create_person(
- team_id=self.team.pk,
- distinct_ids=["person1"],
- properties={"name": "person1"},
- )
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person1",
- timestamp="2020-01-01T12:00:00Z",
- properties={"event_prop": "prop1"},
- )
-
- person2 = _create_person(
- team_id=self.team.pk,
- distinct_ids=["person2"],
- properties={"name": "person2"},
- )
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person2",
- timestamp="2020-01-01T12:00:00Z",
- properties={"event_prop": "prop1"},
- )
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person2",
- timestamp="2020-01-02T12:00:00Z",
- properties={"event_prop": "prop1"},
- )
- # same day
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person2",
- timestamp="2020-01-02T12:00:00Z",
- properties={"event_prop": "prop1"},
- )
-
- person3 = _create_person(
- team_id=self.team.pk,
- distinct_ids=["person3"],
- properties={"name": "person3"},
- )
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person3",
- timestamp="2020-01-01T12:00:00Z",
- properties={"event_prop": "prop2"},
- )
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person3",
- timestamp="2020-01-02T12:00:00Z",
- properties={"event_prop": "prop2"},
- )
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person3",
- timestamp="2020-01-03T12:00:00Z",
- properties={"event_prop": "prop2"},
- )
-
- person4 = _create_person(
- team_id=self.team.pk,
- distinct_ids=["person4"],
- properties={"name": "person4"},
- )
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person4",
- timestamp="2020-01-05T12:00:00Z",
- properties={"event_prop": "prop3"},
- )
- flush_persons_and_events()
- return (person1, person2, person3, person4)
-
- def test_breakdown_by_cohort_people_endpoint(self):
- person1, _, _, _ = self._create_multiple_people()
- cohort = _create_cohort(
- name="cohort1",
- team=self.team,
- groups=[{"properties": [{"key": "name", "value": "person1", "type": "person"}]}],
- )
- _create_cohort(name="cohort2", team=self.team, groups=[{"properties": {"name": "person2"}}])
- _create_cohort(
- name="cohort3",
- team=self.team,
- groups=[
- {"properties": {"name": "person1"}},
- {"properties": {"name": "person2"}},
- ],
- )
- _create_action(name="watched movie", team=self.team)
-
- people = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- "display": TRENDS_CUMULATIVE, # ensure date range is used as is
- ENTITY_TYPE: "events",
- ENTITY_ID: "watched movie",
- "breakdown_type": "cohort",
- "breakdown_value": cohort.pk,
- "breakdown": [cohort.pk], # this shouldn't do anything
- },
- ).json()
-
- self.assertEqual(len(people["results"][0]["people"]), 1)
- ordered_people = sorted(people["results"][0]["people"], key=lambda i: i["id"])
- self.assertEqual(ordered_people[0]["id"], str(person1.uuid))
-
- # all people
- people = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- "display": TRENDS_CUMULATIVE, # ensure date range is used as is
- ENTITY_TYPE: "events",
- ENTITY_ID: "watched movie",
- "breakdown_type": "cohort",
- "breakdown_value": "all",
- "breakdown": [cohort.pk],
- },
- ).json()
-
- self.assertEqual(len(people["results"][0]["people"]), 4)
- ordered_people = sorted(people["results"][0]["people"], key=lambda i: i["created_at"])
- self.assertEqual(ordered_people[0]["id"], str(person1.uuid))
-
- def test_breakdown_by_person_property_people_endpoint(self):
- person1, person2, person3, person4 = self._create_multiple_people()
- _create_action(name="watched movie", team=self.team)
-
- people = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- ENTITY_TYPE: "events",
- ENTITY_ID: "watched movie",
- "properties": json.dumps([{"key": "name", "value": "person3", "type": "person"}]),
- "breakdown_type": "person",
- "breakdown_value": "person3",
- "breakdown": "name",
- },
- ).json()
- self.assertEqual(len(people["results"][0]["people"]), 1)
- self.assertEqual(people["results"][0]["people"][0]["id"], str(person3.uuid))
-
- def test_breakdown_by_event_property_people_endpoint(self):
- person1, person2, person3, person4 = self._create_multiple_people()
- _create_action(name="watched movie", team=self.team)
-
- people = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- ENTITY_TYPE: "events",
- ENTITY_ID: "watched movie",
- "properties": json.dumps([{"key": "event_prop", "value": "prop1", "type": "event"}]),
- "breakdown_type": "event",
- "breakdown_value": "prop1",
- "breakdown": "event_prop",
- },
- ).json()
-
- self.assertEqual(len(people["results"][0]["people"]), 2)
- ordered_people = sorted(p["id"] for p in people["results"][0]["people"])
- self.assertEqual(ordered_people, sorted([str(person1.uuid), str(person2.uuid)]))
-
- def test_filtering_by_person_properties(self):
- person1, person2, person3, person4 = self._create_multiple_people()
-
- people = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- ENTITY_TYPE: "events",
- ENTITY_ID: "watched movie",
- "properties": json.dumps([{"key": "name", "value": "person2", "type": "person"}]),
- },
- ).json()
-
- self.assertEqual(len(people["results"][0]["people"]), 1)
- self.assertEqual(people["results"][0]["people"][0]["id"], str(person2.uuid))
-
- def test_active_user_weekly_people(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-09T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-10T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "p2"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-09T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
-
- people = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-10",
- "date_to": "2020-01-10",
- ENTITY_TYPE: "events",
- ENTITY_ID: "$pageview",
- ENTITY_MATH: "weekly_active",
- },
- ).json()
- self.assertEqual(len(people["results"][0]["people"]), 2)
-
- def test_breakdown_by_person_property_nones_people_endpoint(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-09T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-10T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-09T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-10T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
-
- people = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-10",
- "date_to": "2020-01-10",
- ENTITY_TYPE: "events",
- ENTITY_ID: "$pageview",
- "breakdown_type": "person",
- "breakdown_value": "p1",
- "breakdown": "name",
- },
- ).json()
- self.assertEqual(len(people["results"][0]["people"]), 1)
-
- people = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-10",
- "date_to": "2020-01-10",
- ENTITY_TYPE: "events",
- ENTITY_ID: "$pageview",
- "breakdown_type": "person",
- "breakdown_value": "",
- "breakdown": "name",
- },
- ).json()
- self.assertEqual(len(people["results"][0]["people"]), 1)
-
- def test_breakdown_by_event_property_none_people_endpoint(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-09T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-10T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "p2"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-09T12:00:00Z",
- properties={},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
-
- people = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-8",
- "date_to": "2020-01-12",
- ENTITY_TYPE: "events",
- ENTITY_ID: "$pageview",
- "display": TRENDS_CUMULATIVE, # ensure that the date range is used as is
- "breakdown_type": "event",
- "breakdown_value": "val",
- "breakdown": "key",
- },
- ).json()
- self.assertEqual(len(people["results"][0]["people"]), 2)
-
- people = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-08",
- "date_to": "2020-01-12",
- ENTITY_TYPE: "events",
- ENTITY_ID: "$pageview",
- "display": TRENDS_CUMULATIVE, # ensure that the date range is used as is
- "breakdown_type": "event",
- "breakdown_value": "",
- "breakdown": "key",
- },
- ).json()
- self.assertEqual(len(people["results"][0]["people"]), 1)
-
- @snapshot_clickhouse_queries
- def test_trends_people_endpoint_includes_recordings(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-09T14:00:00Z",
- )
- _create_event(
- event_uuid="693402ed-590e-4737-ba26-93ebf18121bd",
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-09T12:00:00Z",
- properties={"$session_id": "s1", "$window_id": "w1"},
- )
- timestamp = datetime(2020, 1, 9, 12)
- produce_replay_summary(
- team_id=self.team.pk,
- session_id="s1",
- distinct_id="u1",
- first_timestamp=timestamp,
- last_timestamp=timestamp,
- )
-
- people = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={
- "date_from": "2020-01-08",
- "date_to": "2020-01-12",
- ENTITY_TYPE: "events",
- ENTITY_ID: "$pageview",
- "display": TRENDS_CUMULATIVE,
- "breakdown_type": "event",
- "breakdown_value": "",
- "breakdown": "key",
- "include_recordings": "true",
- },
- ).json()
- self.assertEqual(
- people["results"][0]["people"][0]["matched_recordings"],
- [
- {
- "session_id": "s1",
- "events": [
- {
- "window_id": "w1",
- "timestamp": "2020-01-09T12:00:00Z",
- "uuid": "693402ed-590e-4737-ba26-93ebf18121bd",
- }
- ],
- }
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_trends_people_endpoint_filters_search(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["p1"],
- properties={"email": "[email protected]"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-09T14:00:00Z",
- )
-
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["p2"],
- properties={"email": "[email protected]"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-09T14:00:00Z",
- )
-
- params = {
- "date_from": "2020-01-08",
- "date_to": "2020-01-12",
- ENTITY_TYPE: "events",
- ENTITY_ID: "$pageview",
- "display": TRENDS_CUMULATIVE,
- "breakdown_type": "event",
- "breakdown_value": "",
- "breakdown": "key",
- "include_recordings": "true",
- }
-
- people = self.client.get(f"/api/projects/{self.team.id}/persons/trends/", data=params).json()
- assert len(people["results"][0]["people"]) == 2
-
- params["search"] = "ben"
-
- people = self.client.get(f"/api/projects/{self.team.id}/persons/trends/", data=params).json()
- assert len(people["results"][0]["people"]) == 1
diff --git a/posthog/caching/utils.py b/posthog/caching/utils.py
index 49bc260cc19b..c8c9fe6e3a88 100644
--- a/posthog/caching/utils.py
+++ b/posthog/caching/utils.py
@@ -1,16 +1,12 @@
from datetime import UTC, datetime, timedelta
from enum import Enum
-from typing import Any, Optional, Union
+from typing import Optional, Union
from dateutil.parser import isoparse, parser
from posthog.clickhouse.client import sync_execute
from posthog.interval_specs import INTERVAL_SPECS
from posthog.models.event.new_events_schema import events_read_table, use_new_events_schema
-from posthog.models.filters.filter import Filter
-from posthog.models.filters.path_filter import PathFilter
-from posthog.models.filters.retention_filter import RetentionFilter
-from posthog.models.filters.stickiness_filter import StickinessFilter
from posthog.models.team.team import Team
@@ -49,16 +45,6 @@ def last_refresh_from_cached_result(cached_result: dict | object) -> Optional[da
return last_refresh
-def is_stale_filter(
- team: Team,
- filter: Filter | RetentionFilter | StickinessFilter | PathFilter,
- cached_result: Any,
-) -> bool:
- interval = filter.period.lower() if isinstance(filter, RetentionFilter) else filter.interval
- last_refresh = last_refresh_from_cached_result(cached_result)
- return is_stale(team, filter.date_to, interval, last_refresh)
-
-
# enum legacy, default, lazy
class ThresholdMode(Enum):
LEGACY = "legacy"
diff --git a/posthog/decorators.py b/posthog/decorators.py
index 548ed289aa23..048f8899d5a1 100644
--- a/posthog/decorators.py
+++ b/posthog/decorators.py
@@ -1,115 +1,9 @@
from collections.abc import Callable
-from enum import StrEnum
from functools import wraps
-from typing import Any, TypeVar, Union, cast
-
-from django.conf import settings
-from django.urls import resolve
-from django.utils.timezone import now
from loginas.utils import is_impersonated_session
-from prometheus_client import Counter
from rest_framework.request import Request
from rest_framework.response import Response
-from statshog.defaults.django import statsd
-
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.caching.utils import is_stale_filter
-from posthog.clickhouse.query_tagging import tag_queries
-from posthog.hogql_queries.legacy_compatibility.feature_flag import get_query_method
-from posthog.models.filters.utils import get_filter
-from posthog.utils import refresh_requested_by_client
-
-from .utils import generate_cache_key, get_safe_cache
-
-INSIGHT_CACHE_WRITE_COUNTER = Counter("posthog_cloud_insight_cache_write", "A write to the redis insight cache")
-
-
-class CacheType(StrEnum):
- TRENDS = "Trends"
- FUNNEL = "Funnel"
- STICKINESS = "Stickiness"
-
-
-ResultPackage = Union[dict[str, Any], list[dict[str, Any]]]
-
-T = TypeVar("T", bound=ResultPackage)
-U = TypeVar("U", bound=TeamAndOrgViewSetMixin)
-
-
-def cached_by_filters(f: Callable[[U, Request], T]) -> Callable[[U, Request], T]:
- """Caches the decorated method on a ViewSet in Redis. Used for anything based
- on a filter e.g. insights or persons calculations.
-
- The decorated method is expected to return a dict with key `result`. Keys
- `last_refresh` and `is_cached` are added for the full result package.
-
- The cache can be invalidated by using the boolean key `refresh` or setting
- a `cache_invalidation_key` which gets incorporated in the cache key.
- """
-
- @wraps(f)
- def wrapper(self: U, request: Request) -> T:
- from posthog.caching.query_cache_routing import get_query_cache
-
- # prepare caching params
- team = self.team
- if not team:
- return f(self, request)
-
- filter = get_filter(request=request, team=team)
- query_method = get_query_method(request=request, team=team)
- cache_key = f"{filter.toJSON()}_{team.pk}"
-
- if query_method == "hogql":
- cache_key += "_hogql"
-
- if request.data.get("cache_invalidation_key"):
- cache_key += f"_{request.data['cache_invalidation_key']}"
-
- if request.GET.get("cache_invalidation_key"):
- cache_key += f"_{request.GET['cache_invalidation_key']}"
-
- cache_key = generate_cache_key(team.pk, cache_key)
-
- tag_queries(cache_key=cache_key)
-
- # return cached result when possible
- if not refresh_requested_by_client(request):
- cached_result_package = get_safe_cache(cache_key)
-
- # ignore the bare exception warning. we never want this to fail
- # noinspection PyBroadException
- try:
- route = resolve(request.path).route
- except:
- route = "unknown"
-
- if cached_result_package and cached_result_package.get("result"):
- if not is_stale_filter(team, filter, cached_result_package):
- cached_result_package["is_cached"] = True
- statsd.incr("posthog_cached_function_cache_hit", tags={"route": route})
- return cached_result_package
- else:
- statsd.incr("posthog_cached_function_cache_stale", tags={"route": route})
- else:
- statsd.incr("posthog_cached_function_cache_miss", tags={"route": route})
-
- # call function being wrapped
- fresh_result_package = cast(T, f(self, request))
- if isinstance(fresh_result_package, dict):
- result = fresh_result_package.get("result")
- if not isinstance(result, dict) or not result.get("loading"):
- timestamp = now()
- fresh_result_package["last_refresh"] = timestamp # ty: ignore[invalid-assignment]
- fresh_result_package["is_cached"] = False # ty: ignore[invalid-assignment]
- fresh_result_package["query_method"] = query_method # ty: ignore[invalid-assignment]
- get_query_cache().set(cache_key, fresh_result_package, settings.CACHED_RESULTS_TTL)
- INSIGHT_CACHE_WRITE_COUNTER.inc()
-
- return fresh_result_package
-
- return wrapper
def disallow_if_impersonated(
diff --git a/posthog/test/test_decorators.py b/posthog/test/test_decorators.py
index 761f62b7934b..d453fa3b43c6 100644
--- a/posthog/test/test_decorators.py
+++ b/posthog/test/test_decorators.py
@@ -1,11 +1,6 @@
-from datetime import datetime
-from typing import TYPE_CHECKING
-
-from freezegun import freeze_time
-from posthog.test.base import APIBaseTest, BaseTest
+from posthog.test.base import APIBaseTest
from unittest.mock import patch
-from django.core.cache import cache
from django.test import override_settings
from django.urls import include, path
@@ -14,247 +9,7 @@ from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from posthog.api.routing import DefaultRouterPlusPlus
-from posthog.decorators import cached_by_filters, disallow_if_impersonated, is_stale_filter
-from posthog.models.filters.filter import Filter
-from posthog.models.filters.path_filter import PathFilter
-from posthog.models.filters.retention_filter import RetentionFilter
-from posthog.models.filters.stickiness_filter import StickinessFilter
-from posthog.models.team.team import Team
-
-if TYPE_CHECKING:
- from posthog.api.routing import TeamAndOrgViewSetMixin
-
-
-class DummyViewSet(*((TeamAndOrgViewSetMixin, GenericViewSet) if TYPE_CHECKING else (GenericViewSet,))): # type: ignore
- # We don't actually want TeamAndOrgViewSetMixin's functionality in this class, but we do pretend to act like
- # TeamAndOrgViewSetMixin in terms of having `team`. To make mypy happy, we make it _think_ that the mixin is used
- team: Team
-
- def list(self, request):
- data = self.calculate_with_filters(request)
- return Response(data)
-
- @cached_by_filters
- def calculate_with_filters(self, request):
- return {"result": "bla"}
-
-
-@override_settings(ROOT_URLCONF="posthog.test.test_decorators")
-class TestCachedByFiltersDecorator(APIBaseTest):
- def setUp(self) -> None:
- DummyViewSet.team = self.team # Simulating TeamAndOrgViewSetMixin
- cache.clear()
- super().setUp()
-
- def test_returns_fresh_result(self) -> None:
- response = self.client.get(f"/api/dummy").json()
-
- assert response["result"] == "bla"
- assert response["is_cached"] is False
- assert isinstance(response["last_refresh"], str)
-
- def test_returns_cached_result(self) -> None:
- # Prime the cache
- self.client.get(f"/api/dummy").json()
-
- response = self.client.get(f"/api/dummy").json()
-
- assert response["result"] == "bla"
- assert response["is_cached"] is True
-
- def test_team_id_from_viewset_is_used(self) -> None:
- other_team = Team.objects.create(organization=self.organization)
-
- # Prime the cache
- self.client.get(f"/api/dummy").json()
-
- # Now switch to the other team - cache should be different
- DummyViewSet.team = other_team
-
- response_for_other_team_initial = self.client.get(f"/api/dummy").json()
- response_for_other_team_repeated = self.client.get(f"/api/dummy").json()
-
- assert response_for_other_team_initial["result"] == "bla"
- assert response_for_other_team_initial["is_cached"] is False
- assert response_for_other_team_repeated["result"] == "bla"
- assert response_for_other_team_repeated["is_cached"] is True
-
- def test_cache_bypass_with_refresh_param(self) -> None:
- # Prime the cache
- self.client.get(f"/api/dummy").json()
-
- response = self.client.get(f"/api/dummy", data={"refresh": "true"}).json()
-
- assert response["is_cached"] is False
-
- def test_cache_bypass_with_invalidation_key_param(self) -> None:
- # Prime the cache
- self.client.get(f"/api/dummy").json()
-
- response = self.client.get(f"/api/dummy", data={"cache_invalidation_key": "abc"}).json()
-
- assert response["is_cached"] is False
-
- def test_discards_stale_response(self) -> None:
- with freeze_time("2023-02-08T12:05:23Z"):
- # Prime the cache
- self.client.get(f"/api/dummy").json()
-
- with freeze_time("2023-02-10T12:00:00Z"):
- # we don't need to add filters, since -7d with a
- # daily interval is the default
- response = self.client.get(f"/api/dummy").json()
- assert response["is_cached"] is False
-
-
-class TestIsStaleHelper(BaseTest):
- cached_response = {
- "last_refresh": datetime.fromisoformat("2023-02-08T12:05:23+00:00"),
- "result": "bla",
- }
-
- def test_keeps_fresh_hourly_result(self) -> None:
- with freeze_time("2023-02-08T12:15:59Z"):
- filter = Filter(data={"interval": "hour"})
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is False
-
- def test_discards_stale_hourly_result(self) -> None:
- with freeze_time("2023-02-08T13:06:00Z"):
- filter = Filter(data={"interval": "hour"})
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is True
-
- def test_keeps_fresh_daily_result(self) -> None:
- with freeze_time("2023-02-08T13:59:59Z"):
- filter = Filter(data={"interval": "day"})
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is False
-
- def test_discards_stale_daily_result(self) -> None:
- with freeze_time("2023-02-09T00:00:00Z"):
- filter = Filter(data={"interval": "day"})
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is True
-
- def test_keeps_fresh_weekly_result(self) -> None:
- with freeze_time("2023-02-09T00:04:59Z"):
- filter = Filter(data={"interval": "week"})
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is False
-
- def test_discards_stale_weekly_result(self) -> None:
- with freeze_time("2023-02-12T00:00:00Z"):
- filter = Filter(data={"interval": "week"})
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is True
-
- def test_keeps_fresh_monthly_result(self) -> None:
- with freeze_time("2023-02-08T12:04:59Z"):
- filter = Filter(data={"interval": "month"})
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is False
-
- def test_discards_stale_monthly_result(self) -> None:
- with freeze_time("2023-03-01T00:00:00Z"):
- filter = Filter(data={"interval": "month"})
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is True
-
- def test_keeps_fresh_result_from_fixed_range(self) -> None:
- filter = Filter(data={"interval": "day", "date_from": "2000-01-01", "date_to": "2000-01-10"})
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is False
-
- def test_keeps_fresh_result_with_date_to_in_future(self) -> None:
- with freeze_time("2023-02-08T12:15:59Z"):
- filter = Filter(data={"interval": "day", "date_to": "2999-01-01"})
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is False
-
- def test_keeps_fresh_stickiness_result(self) -> None:
- with freeze_time("2023-02-08T12:15:59Z"):
- filter = StickinessFilter(data={}, team=self.team)
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is False
-
- def test_discards_stale_stickiness_result(self) -> None:
- with freeze_time("2023-02-09T00:00:00Z"):
- filter = StickinessFilter(data={}, team=self.team)
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is True
-
- def test_keeps_fresh_path_result(self) -> None:
- with freeze_time("2023-02-08T12:15:59Z"):
- filter = PathFilter()
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is False
-
- def test_discards_stale_path_result(self) -> None:
- with freeze_time("2023-02-09T00:00:00Z"):
- filter = PathFilter()
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is True
-
- def test_keeps_fresh_retention_hourly_result(self) -> None:
- with freeze_time("2023-02-08T12:15:59Z"):
- filter = RetentionFilter(data={"period": "Hour"})
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is False
-
- def test_discards_stale_retention_hourly_result(self) -> None:
- with freeze_time("2023-02-08T13:06:00Z"):
- filter = RetentionFilter(data={"period": "Hour"})
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is True
-
- def test_keeps_fresh_retention_result(self) -> None:
- with freeze_time("2023-02-08T12:15:59Z"):
- filter = RetentionFilter()
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is False
-
- def test_discards_stale_retention_result(self) -> None:
- with freeze_time("2023-02-09T00:00:00Z"):
- filter = RetentionFilter()
-
- stale = is_stale_filter(self.team, filter, self.cached_response)
-
- assert stale is True
+from posthog.decorators import disallow_if_impersonated
class ImpersonationTestViewSet(GenericViewSet):
@@ -281,7 +36,6 @@ class ImpersonationTestViewSet(GenericViewSet):
# routes exist exactly for these tests, in any order, and stops them leaking into the real
# URL space of every other test in the process.
_test_router = DefaultRouterPlusPlus()
-_test_router.register(r"dummy", DummyViewSet, "dummy")
_test_router.register(r"impersonation-test", ImpersonationTestViewSet, "impersonation-test")
urlpatterns = [path("api/", include(_test_router.urls))]
diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.ts
index 723bab1694dc..1b7bc5aa5ffd 100644
--- a/products/persons/frontend/generated/api.schemas.ts
+++ b/products/persons/frontend/generated/api.schemas.ts
@@ -657,28 +657,6 @@ export const PersonsDeletionStatusListStatus = {
Pending: 'pending',
} as const
-export type PersonsFunnelRetrieveParams = {
- format?: PersonsFunnelRetrieveFormat
-}
-
-export type PersonsFunnelRetrieveFormat = (typeof PersonsFunnelRetrieveFormat)[keyof typeof PersonsFunnelRetrieveFormat]
-
-export const PersonsFunnelRetrieveFormat = {
- Csv: 'csv',
- Json: 'json',
-} as const
-
-export type PersonsFunnelCreateParams = {
- format?: PersonsFunnelCreateFormat
-}
-
-export type PersonsFunnelCreateFormat = (typeof PersonsFunnelCreateFormat)[keyof typeof PersonsFunnelCreateFormat]
-
-export const PersonsFunnelCreateFormat = {
- Csv: 'csv',
- Json: 'json',
-} as const
-
export type PersonsLifecycleRetrieveParams = {
format?: PersonsLifecycleRetrieveFormat
}
@@ -731,17 +709,6 @@ export const PersonsResetPersonDistinctIdCreateFormat = {
Json: 'json',
} as const
-export type PersonsTrendsRetrieveParams = {
- format?: PersonsTrendsRetrieveFormat
-}
-
-export type PersonsTrendsRetrieveFormat = (typeof PersonsTrendsRetrieveFormat)[keyof typeof PersonsTrendsRetrieveFormat]
-
-export const PersonsTrendsRetrieveFormat = {
- Csv: 'csv',
- Json: 'json',
-} as const
-
export type PersonsValuesRetrieveParams = {
format?: PersonsValuesRetrieveFormat
/**
diff --git a/products/persons/frontend/generated/api.ts b/products/persons/frontend/generated/api.ts
index 2ab0a4d3d246..8b5cdd995e39 100644
--- a/products/persons/frontend/generated/api.ts
+++ b/products/persons/frontend/generated/api.ts
@@ -30,8 +30,6 @@ import type {
PersonsDeletePropertyCreateParams,
PersonsDeletionStatusListParams,
PersonsEmailsListParams,
- PersonsFunnelCreateParams,
- PersonsFunnelRetrieveParams,
PersonsLifecycleRetrieveParams,
PersonsListParams,
PersonsPartialUpdateParams,
@@ -40,7 +38,6 @@ import type {
PersonsResetPersonDistinctIdCreateParams,
PersonsRetrieveParams,
PersonsSplitCreateParams,
- PersonsTrendsRetrieveParams,
PersonsUpdateParams,
PersonsUpdatePropertyCreateParams,
PersonsValuesRetrieveParams,
@@ -604,69 +601,6 @@ export const personsDeletionStatusList = async (
})
}
-export const getPersonsFunnelRetrieveUrl = (projectId: string, params?: PersonsFunnelRetrieveParams) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : String(value))
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/persons/funnel/?${stringifiedParams}`
- : `/api/projects/${projectId}/persons/funnel/`
-}
-
-/**
- * This endpoint is meant for reading and deleting persons. To create or update persons, we recommend using the [capture API](https://posthog.com/docs/api/capture), the `$set` and `$unset` [properties](https://posthog.com/docs/product-analytics/user-properties), or one of our SDKs.
- */
-export const personsFunnelRetrieve = async (
- projectId: string,
- params?: PersonsFunnelRetrieveParams,
- options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getPersonsFunnelRetrieveUrl(projectId, params), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getPersonsFunnelCreateUrl = (projectId: string, params?: PersonsFunnelCreateParams) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : String(value))
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/persons/funnel/?${stringifiedParams}`
- : `/api/projects/${projectId}/persons/funnel/`
-}
-
-/**
- * This endpoint is meant for reading and deleting persons. To create or update persons, we recommend using the [capture API](https://posthog.com/docs/api/capture), the `$set` and `$unset` [properties](https://posthog.com/docs/product-analytics/user-properties), or one of our SDKs.
- */
-export const personsFunnelCreate = async (
- projectId: string,
- personRecordApi?: NonReadonly<PersonRecordApi>,
- params?: PersonsFunnelCreateParams,
- options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getPersonsFunnelCreateUrl(projectId, params), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(personRecordApi),
- })
-}
-
export const getPersonsLifecycleRetrieveUrl = (projectId: string, params?: PersonsLifecycleRetrieveParams) => {
const normalizedParams = new URLSearchParams()
@@ -774,36 +708,6 @@ export const personsResetPersonDistinctIdCreate = async (
})
}
-export const getPersonsTrendsRetrieveUrl = (projectId: string, params?: PersonsTrendsRetrieveParams) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : String(value))
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/persons/trends/?${stringifiedParams}`
- : `/api/projects/${projectId}/persons/trends/`
-}
-
-/**
- * This endpoint is meant for reading and deleting persons. To create or update persons, we recommend using the [capture API](https://posthog.com/docs/api/capture), the `$set` and `$unset` [properties](https://posthog.com/docs/product-analytics/user-properties), or one of our SDKs.
- */
-export const personsTrendsRetrieve = async (
- projectId: string,
- params?: PersonsTrendsRetrieveParams,
- options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getPersonsTrendsRetrieveUrl(projectId, params), {
- ...options,
- method: 'GET',
- })
-}
-
export const getPersonsValuesRetrieveUrl = (projectId: string, params: PersonsValuesRetrieveParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/persons/frontend/generated/api.zod.ts b/products/persons/frontend/generated/api.zod.ts
index 936aac81f73b..220c34818a86 100644
--- a/products/persons/frontend/generated/api.zod.ts
+++ b/products/persons/frontend/generated/api.zod.ts
@@ -118,16 +118,6 @@ export const PersonsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({
.describe('If true, keep the person records but delete their events and recordings.'),
})
-/**
- * This endpoint is meant for reading and deleting persons. To create or update persons, we recommend using the [capture API](https://posthog.com/docs/api/capture), the `$set` and `$unset` [properties](https://posthog.com/docs/product-analytics/user-properties), or one of our SDKs.
- */
-export const PersonsFunnelCreateBody = /* @__PURE__ */ zod.object({
- properties: zod
- .unknown()
- .optional()
- .describe('Key-value map of person properties set via $set and $set_once operations.'),
-})
-
/**
* Reset a distinct_id for a deleted person. This allows the distinct_id to be used again.
*/
diff --git a/products/persons/mcp/tools.yaml b/products/persons/mcp/tools.yaml
index 549fc59f8c76..a3abfbaf9b50 100644
--- a/products/persons/mcp/tools.yaml
+++ b/products/persons/mcp/tools.yaml
@@ -58,12 +58,6 @@ tools:
persons-emails-list:
operation: persons_emails_list
enabled: false
- persons-funnel-create:
- operation: persons_funnel_create
- enabled: false
- persons-funnel-retrieve:
- operation: persons_funnel_retrieve
- enabled: false
persons-lifecycle-retrieve:
operation: persons_lifecycle_retrieve
enabled: false
@@ -172,9 +166,6 @@ tools:
persons-split-create:
operation: persons_split_create
enabled: false
- persons-trends-retrieve:
- operation: persons_trends_retrieve
- enabled: false
persons-update:
operation: persons_update
enabled: false
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index b8a362147340..d68216be16e1 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -2341,7 +2341,7 @@ When set, the specified dashboard's filters and date range override will be appl
) -> dict[str, Any]:
"""Convert Filter-style params to a query and run via process_query_dict.
- Uses the unified QueryRunner cache instead of the legacy @cached_by_filters system.
+ Uses the unified QueryRunner cache instead of the removed legacy filter-based cache.
"""
team = self.team
filter = Filter(request=request, team=team)
diff --git a/products/product_analytics/backend/api/insight_serializers.py b/products/product_analytics/backend/api/insight_serializers.py
deleted file mode 100644
index 0a1232b36f81..000000000000
--- a/products/product_analytics/backend/api/insight_serializers.py
+++ /dev/null
@@ -1,245 +0,0 @@
-import json
-from typing import get_args
-
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import extend_schema_field
-from rest_framework import serializers
-
-from posthog.api.documentation import (
- FilterActionSerializer,
- FilterEventSerializer,
- PropertySerializer,
- property_help_text,
-)
-from posthog.constants import (
- ACTIONS,
- BREAKDOWN_TYPES,
- DISPLAY_TYPES,
- EVENTS,
- FUNNEL_WINDOW_INTERVAL_TYPES,
- PROPERTIES,
- FunnelOrderType,
- FunnelVizType,
-)
-from posthog.models.team import TIMEZONES
-
-
-class GenericInsightsSerializer(serializers.Serializer):
- def __init__(self, request=None, *args, **kwargs):
- if request:
- data = {**request.data, **request.GET.dict()}
- if data.get(ACTIONS):
- actions = data.get(ACTIONS, [])
- if isinstance(actions, str):
- actions = json.loads(actions)
- data["actions"] = actions
- if data.get(EVENTS):
- events = data.get(EVENTS, [])
- if isinstance(events, str):
- events = json.loads(events)
- data["events"] = events
- if data.get(PROPERTIES):
- properties = data.get(PROPERTIES, [])
- if isinstance(properties, str):
- properties = json.loads(properties)
- data["properties"] = properties
- kwargs["data"] = data
-
- super().__init__(*args, **kwargs)
-
- events = FilterEventSerializer(
- required=False,
- many=True,
- help_text="Events to filter on. One of `events` or `actions` is required.",
- )
- actions = FilterActionSerializer(
- required=False,
- many=True,
- help_text="Actions to filter on. One of `events` or `actions` is required.",
- )
- properties = PropertySerializer(required=False, help_text=property_help_text)
- filter_test_accounts = serializers.BooleanField(
- help_text='Whether to filter out internal and test accounts. See "project settings" in your PostHog account for the filters.',
- default=False,
- )
- date_from = serializers.CharField(
- required=False,
- help_text="What date to filter the results from. Can either be a date `2021-01-01`, or a relative date, like `-7d` for last seven days, `-1m` for last month, `mStart` for start of the month or `yStart` for the start of the year.",
- default="-7d",
- )
- date_to = serializers.CharField(
- required=False,
- help_text="What date to filter the results to. Can either be a date `2021-01-01`, or a relative date, like `-7d` for last seven days, `-1m` for last month, `mStart` for start of the month or `yStart` for the start of the year.",
- default="-7d",
- )
-
-
-@extend_schema_field(OpenApiTypes.STR)
-class BreakdownField(serializers.Field):
- def to_representation(self, value):
- return value
-
- def to_internal_value(self, data):
- return data
-
-
-class BreakdownMixin(serializers.Serializer):
- breakdown = BreakdownField(
- required=False,
- help_text="""A property or cohort to break down on. You can select the type of the property with breakdown_type.
-- `event` (default): a property key
-- `person`: a person property key
-- `cohort`: an array of cohort IDs (ie `[9581,5812]`)""",
- )
- breakdown_type = serializers.ChoiceField(
- choices=get_args(BREAKDOWN_TYPES),
- required=False,
- help_text="Type of property to break down on.",
- default="event",
- )
-
- def validate(self, data):
- breakdown_type = data.get("breakdown_type", "event")
-
- if breakdown_type == "cohort":
- if (
- data.get("breakdown")
- and not isinstance(data["breakdown"], list)
- or any(not isinstance(item, int) for item in data["breakdown"])
- ):
- raise serializers.ValidationError("If breakdown_type is cohort, breakdown must be a list of numbers")
-
- if (
- (breakdown_type == "event" or data["breakdown_type"] == "person")
- and data.get("breakdown")
- and not isinstance(data["breakdown"], str)
- ):
- raise serializers.ValidationError("If breakdown_type is event or person, breakdown must be a property key")
- return super().validate(data)
-
-
-class CompareMixin(serializers.Serializer):
- compare = serializers.BooleanField(required=False, help_text="To compare or not")
- compare_to = serializers.CharField(
- required=False,
- help_text="What to compare to",
- )
-
-
-class ResultsMixin(serializers.Serializer):
- is_cached = serializers.BooleanField(
- help_text="Whether the result is cached. To force a refresh, pass ?refresh=true"
- )
- last_refresh = serializers.DateTimeField(help_text="If the result is cached, when it was last refreshed.")
- timezone = serializers.ChoiceField(choices=TIMEZONES, default="UTC", help_text="Timezone the chart is displayed in")
-
-
-class TrendResultSerializer(serializers.Serializer):
- data = serializers.ListField(child=serializers.IntegerField(), help_text="The requested counts.") # type: ignore
- days = serializers.ListField(
- child=serializers.DateField(),
- help_text="The dates corresponding to the data field above.",
- )
- labels = serializers.ListField(
- child=serializers.CharField(),
- help_text="The dates corresponding to the data field above.",
- )
- filter = GenericInsightsSerializer(help_text="The insight that's being returned.")
- label = serializers.CharField(
- help_text="A label describing this result. Will include\n- The event or action\n- Breakdown value\n- If `compare:true`, whether it's `current` or `previous`"
- ) # type: ignore
-
-
-class TrendResultsSerializer(ResultsMixin):
- result = TrendResultSerializer(many=True)
-
-
-class TrendSerializer(GenericInsightsSerializer, BreakdownMixin, CompareMixin):
- display = serializers.ChoiceField(
- choices=get_args(DISPLAY_TYPES),
- required=False,
- default="ActionsLineGraph",
- help_text="How to display the data. Will change how the data is returned.",
- )
-
- formula = serializers.CharField(
- required=False,
- help_text="Combine the result of events or actions into a single number. For example `A + B` or `(A-B)/B`. The letters correspond to the order of the `events` or `actions` lists.",
- allow_blank=True,
- )
-
-
-class FunnelExclusionSerializer(serializers.Serializer):
- id = serializers.CharField(help_text="Name of the event to filter on. For example `$pageview` or `user sign up`.")
- properties = PropertySerializer(required=False, help_text=property_help_text)
- funnel_from_step = serializers.IntegerField(default=0, required=False)
- funnel_to_step = serializers.IntegerField(default=1, required=False)
-
-
-class FunnelStepsResultSerializer(serializers.Serializer):
- count = serializers.IntegerField(help_text="Number of people in this step.")
- action_id = serializers.CharField(
- help_text="Corresponds to the `id` of the entities passed through to `events` or `actions`."
- )
- average_conversion_time = serializers.FloatField(
- help_text="Average conversion time of person or groups between steps. `null` for the first step."
- )
- median_conversion_time = serializers.FloatField(
- help_text="Median conversion time of person or groups between steps. `null` for the first step."
- )
- converted_people_url = serializers.CharField(
- help_text="Path of a URL to get a list of people that converted after this step. In this format: `/api/person/funnel?...`"
- )
- dropped_people_url = serializers.CharField(
- help_text="Path of a URL to get a list of people that dropped after this step. In this format: `/api/person/funnel?...`"
- )
- order = serializers.CharField(
- help_text="Order of this step in the funnel. The API should return the steps in order anyway."
- )
- # Fields not added to this serializer for simplicity: custom_name, name, order, people, type
-
-
-class FunnelStepsResultsSerializer(ResultsMixin):
- result = FunnelStepsResultSerializer(many=True)
-
-
-class FunnelSerializer(GenericInsightsSerializer, BreakdownMixin):
- funnel_window_interval = serializers.IntegerField(
- help_text="Funnel window size. Set in combination with funnel_window_interval_type, so defaults to 'DAY'.",
- required=False,
- default=14,
- )
- funnel_window_interval_type = serializers.ChoiceField(
- choices=get_args(FUNNEL_WINDOW_INTERVAL_TYPES),
- required=False,
- help_text="The type of interval. Used in combination with `funnel_window_interval`.",
- default="DAY",
- )
- funnel_viz_type = serializers.ChoiceField(
- choices=[el.value for el in FunnelVizType],
- required=False,
- help_text="The visualisation type.\n- `steps` Track instances progress between steps of the funnel\n- `trends` Track how this funnel's conversion rate is trending over time.\n- `time_to_convert` Track how long it takes for instances to convert",
- default="steps",
- )
- funnel_order_type = serializers.ChoiceField(
- choices=[el.value for el in FunnelOrderType],
- required=False,
- help_text="- `ordered` - Step B must happen after Step A, but any number events can happen between A and B.\n- `strict` - Step B must happen directly after Step A without any events in between.\n- `unordered` - Steps can be completed in any sequence.",
- default="ordered",
- )
- exclusions = FunnelExclusionSerializer(
- many=True,
- required=False,
- help_text="Exclude users/groups that completed the specified event between two specific steps. Note that these users/groups will be completely excluded from the entire funnel.",
- )
- aggregation_group_type_index = serializers.IntegerField(
- help_text="Aggregate by users or by groups. `0` means user, `>0` means a group. See interface for the corresponding ID of the group.",
- default=0,
- required=False,
- )
- breakdown_limit = serializers.IntegerField(help_text="", required=False, default=10)
- funnel_window_days = serializers.IntegerField(
- help_text="(DEPRECATED) Funnel window size in days. Use `funnel_window_interval` and `funnel_window_interval_type`",
- required=False,
- default=14,
- )
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 669c6d5d58ca..68f01aa6504e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -78532,30 +78532,6 @@ export namespace Schemas {
Pending: 'pending',
} as const;
- export type PersonsFunnelRetrieveParams = {
- format?: PersonsFunnelRetrieveFormat;
- };
-
- export type PersonsFunnelRetrieveFormat = typeof PersonsFunnelRetrieveFormat[keyof typeof PersonsFunnelRetrieveFormat];
-
-
- export const PersonsFunnelRetrieveFormat = {
- Csv: 'csv',
- Json: 'json',
- } as const;
-
- export type PersonsFunnelCreateParams = {
- format?: PersonsFunnelCreateFormat;
- };
-
- export type PersonsFunnelCreateFormat = typeof PersonsFunnelCreateFormat[keyof typeof PersonsFunnelCreateFormat];
-
-
- export const PersonsFunnelCreateFormat = {
- Csv: 'csv',
- Json: 'json',
- } as const;
-
export type PersonsLifecycleRetrieveParams = {
format?: PersonsLifecycleRetrieveFormat;
};
@@ -78608,18 +78584,6 @@ export namespace Schemas {
Json: 'json',
} as const;
- export type PersonsTrendsRetrieveParams = {
- format?: PersonsTrendsRetrieveFormat;
- };
-
- export type PersonsTrendsRetrieveFormat = typeof PersonsTrendsRetrieveFormat[keyof typeof PersonsTrendsRetrieveFormat];
-
-
- export const PersonsTrendsRetrieveFormat = {
- Csv: 'csv',
- Json: 'json',
- } as const;
-
export type PersonsValuesRetrieveParams = {
format?: PersonsValuesRetrieveFormat;
/**