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(insights): remove the legacy trend and funnel endpoints (#97647)

Thomas Obermüller17c67164a667
diff --git a/ee/clickhouse/materialized_columns/test/test_query.py b/ee/clickhouse/materialized_columns/test/test_query.py
index d578d37bf29e..e1c21a634a14 100644
--- a/ee/clickhouse/materialized_columns/test/test_query.py
+++ b/ee/clickhouse/materialized_columns/test/test_query.py
@@ -6,16 +6,8 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
# some random
with self.capture_select_queries() as queries:
self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "events": [
- {"id": "step one", "type": "events", "order": 0},
- {"id": "step two", "type": "events", "order": 1},
- ],
- "funnel_window_days": 14,
- "funnel_order_type": "unordered",
- "insight": "funnels",
- },
+ f"/api/projects/{self.team.id}/query/",
+ {"query": {"kind": "HogQLQuery", "query": "select count() from events"}},
).json()
self.assertTrue(len(queries))
diff --git a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_trends.ambr b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_trends.ambr
deleted file mode 100644
index 974f4444af29..000000000000
--- a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_trends.ambr
+++ /dev/null
@@ -1,551 +0,0 @@
-# serializer version: 1
-# name: ClickhouseTestTrends.test_insight_trends_aggregate
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT count() AS total
- FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- ORDER BY 1 DESC
- LIMIT 50000 SETTINGS 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: ClickhouseTestTrends.test_insight_trends_basic
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start
- FROM
- (SELECT count(DISTINCT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)) AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
- 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)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- GROUP BY day_start)
- GROUP BY day_start
- ORDER BY day_start ASC)
- ORDER BY arraySum(total) DESC
- LIMIT 50000 SETTINGS 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: ClickhouseTestTrends.test_insight_trends_cumulative
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date)) AS total
- FROM
- (SELECT day_start AS day_start,
- sum(count) OVER (
- ORDER BY day_start ASC) AS count
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start
- FROM
- (SELECT count() AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
- FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- GROUP BY day_start)
- GROUP BY day_start
- ORDER BY day_start ASC)
- ORDER BY day_start ASC)
- ORDER BY arraySum(total) DESC
- LIMIT 50000 SETTINGS 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: ClickhouseTestTrends.test_insight_trends_cumulative.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date)) AS total
- FROM
- (SELECT day_start AS day_start,
- sum(count) OVER (
- ORDER BY day_start ASC) AS count
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start
- FROM
- (SELECT count(DISTINCT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)) AS total,
- min(toStartOfDay(toTimeZone(e.timestamp, 'UTC'))) AS day_start
- 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)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- GROUP BY if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id))
- GROUP BY day_start
- ORDER BY day_start ASC)
- ORDER BY day_start ASC)
- ORDER BY arraySum(total) DESC
- LIMIT 50000 SETTINGS 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: ClickhouseTestTrends.test_insight_trends_cumulative.2
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT groupArray(1)(date)[1] AS date,
- arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,
- if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value
- FROM
- (SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date)) AS total,
- breakdown_value AS breakdown_value,
- rowNumberInAllBlocks() AS row_number
- FROM
- (SELECT day_start AS day_start,
- sum(count) OVER (PARTITION BY breakdown_value
- ORDER BY day_start ASC) AS count,
- breakdown_value AS breakdown_value
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start,
- breakdown_value AS breakdown_value
- FROM
- (SELECT count() AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start,
- ifNull(nullIf(leftUTF8(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'key'), ''), 'null'), '^"|"$', '')), 400), ''), '$$_posthog_breakdown_null_$$') AS breakdown_value
- FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- GROUP BY day_start,
- breakdown_value)
- GROUP BY day_start,
- breakdown_value
- ORDER BY day_start ASC,
- breakdown_value ASC)
- ORDER BY day_start ASC)
- GROUP BY breakdown_value
- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)
- WHERE isNotNull(breakdown_value)
- GROUP BY breakdown_value
- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC
- LIMIT 50000 SETTINGS 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: ClickhouseTestTrends.test_insight_trends_cumulative.3
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT groupArray(1)(date)[1] AS date,
- arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,
- if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value
- FROM
- (SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date)) AS total,
- breakdown_value AS breakdown_value,
- rowNumberInAllBlocks() AS row_number
- FROM
- (SELECT day_start AS day_start,
- sum(count) OVER (PARTITION BY breakdown_value
- ORDER BY day_start ASC) AS count,
- breakdown_value AS breakdown_value
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start,
- breakdown_value AS breakdown_value
- FROM
- (SELECT counts AS total,
- toStartOfDay(timestamp) AS day_start,
- breakdown_value AS breakdown_value
- FROM
- (SELECT d.timestamp AS timestamp,
- count(DISTINCT e.actor_id) AS counts,
- e.breakdown_value AS breakdown_value
- FROM
- (SELECT toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS timestamp,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS actor_id,
- ifNull(nullIf(leftUTF8(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'key'), ''), 'null'), '^"|"$', '')), 400), ''), '$$_posthog_breakdown_null_$$') AS breakdown_value
- 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)
- WHERE and(equals(e.team_id, 99999), and(equals(e.event, '$pageview'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'key'), ''), 'null'), '^"|"$', ''), 'some_val'), 0), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'key'), ''), 'null'), '^"|"$', ''), 'some_val'), 0)), greaterOrEquals(timestamp, minus(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(7))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))))
- GROUP BY timestamp, actor_id,
- breakdown_value) AS e
- CROSS JOIN
- (SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestamp
- FROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')))) AS numbers) AS d
- WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))
- GROUP BY d.timestamp,
- breakdown_value
- ORDER BY d.timestamp ASC)
- WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')))))
- GROUP BY day_start,
- breakdown_value
- ORDER BY day_start ASC,
- breakdown_value ASC)
- ORDER BY day_start ASC)
- GROUP BY breakdown_value
- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)
- WHERE isNotNull(breakdown_value)
- GROUP BY breakdown_value
- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC
- LIMIT 50000 SETTINGS 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: ClickhouseTestTrends.test_insight_trends_cumulative.4
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT groupArray(1)(date)[1] AS date,
- arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,
- if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value
- FROM
- (SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date)) AS total,
- breakdown_value AS breakdown_value,
- rowNumberInAllBlocks() AS row_number
- FROM
- (SELECT day_start AS day_start,
- sum(count) OVER (PARTITION BY breakdown_value
- ORDER BY day_start ASC) AS count,
- breakdown_value AS breakdown_value
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start,
- breakdown_value AS breakdown_value
- FROM
- (SELECT count(DISTINCT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)) AS total,
- min(toStartOfDay(toTimeZone(e.timestamp, 'UTC'))) AS day_start,
- ifNull(nullIf(leftUTF8(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'key'), ''), 'null'), '^"|"$', '')), 400), ''), '$$_posthog_breakdown_null_$$') AS breakdown_value
- 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)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- GROUP BY if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id),
- breakdown_value)
- GROUP BY day_start,
- breakdown_value
- ORDER BY day_start ASC,
- breakdown_value ASC)
- ORDER BY day_start ASC)
- GROUP BY breakdown_value
- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)
- WHERE isNotNull(breakdown_value)
- GROUP BY breakdown_value
- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC
- LIMIT 50000 SETTINGS 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: ClickhouseTestTrendsCaching.test_insight_trends_merging
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start
- FROM
- (SELECT count(DISTINCT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)) AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
- 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)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- GROUP BY day_start)
- GROUP BY day_start
- ORDER BY day_start ASC)
- ORDER BY arraySum(total) DESC
- LIMIT 50000 SETTINGS 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: ClickhouseTestTrendsCaching.test_insight_trends_merging.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start
- FROM
- (SELECT count(DISTINCT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)) AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
- 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)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- GROUP BY day_start)
- GROUP BY day_start
- ORDER BY day_start ASC)
- ORDER BY arraySum(total) DESC
- LIMIT 50000 SETTINGS 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: ClickhouseTestTrendsCaching.test_insight_trends_merging_skipped_interval
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2011-12-31 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2011-12-31 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-14 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start
- FROM
- (SELECT count(DISTINCT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)) AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
- 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)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2011-12-31 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-14 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- GROUP BY day_start)
- GROUP BY day_start
- ORDER BY day_start ASC)
- ORDER BY arraySum(total) DESC
- LIMIT 50000 SETTINGS 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: ClickhouseTestTrendsCaching.test_insight_trends_merging_skipped_interval.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-02 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-02 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-16 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start
- FROM
- (SELECT count(DISTINCT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)) AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
- 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)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-02 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-16 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- GROUP BY day_start)
- GROUP BY day_start
- ORDER BY day_start ASC)
- ORDER BY arraySum(total) DESC
- LIMIT 50000 SETTINGS 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: ClickhouseTestTrendsGroups.test_aggregating_by_group
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start
- FROM
- (SELECT count(DISTINCT e.`$group_0`) AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
- FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC'))), equals(e.event, '$pageview'), ifNull(notEquals(nullIf(nullIf(e.`$group_0`, ''), 'null'), ''), 1), notEquals(e.`$group_0`, ''))
- GROUP BY day_start)
- GROUP BY day_start
- ORDER BY day_start ASC)
- ORDER BY arraySum(total) DESC
- LIMIT 50000 SETTINGS 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: ClickhouseTestTrendsGroups.test_aggregating_by_session
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start
- FROM
- (SELECT count(DISTINCT e.`$session_id`) AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
- FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- GROUP BY day_start)
- GROUP BY day_start
- ORDER BY day_start ASC)
- ORDER BY arraySum(total) DESC
- LIMIT 50000 SETTINGS 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/__init__.py b/ee/clickhouse/views/test/funnel/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel.ambr b/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel.ambr
deleted file mode 100644
index 87a91fbb9534..000000000000
--- a/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel.ambr
+++ /dev/null
@@ -1,511 +0,0 @@
-# serializer version: 1
-# name: ClickhouseTestFunnelGroups.test_funnel_aggregation_with_groups
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT countIf(ifNull(equals(steps, 1), 0)) AS step_1,
- countIf(ifNull(equals(steps, 2), 0)) AS step_2,
- avg(step_1_average_conversion_time_inner) AS step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) AS step_1_median_conversion_time
- FROM
- (SELECT aggregation_target AS aggregation_target,
- steps AS steps,
- avg(step_1_conversion_time) AS step_1_average_conversion_time_inner,
- median(step_1_conversion_time) AS step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target AS aggregation_target,
- steps AS steps,
- max(steps) OVER (PARTITION BY aggregation_target) AS max_steps,
- step_1_conversion_time AS step_1_conversion_time
- FROM
- (SELECT aggregation_target AS aggregation_target,
- timestamp AS timestamp,
- step_0 AS step_0,
- latest_0 AS latest_0,
- step_1 AS step_1,
- latest_1 AS latest_1,
- if(and(ifNull(lessOrEquals(latest_0, latest_1), 0), ifNull(lessOrEquals(latest_1, plus(toTimeZone(latest_0, 'UTC'), toIntervalDay(14))), 0)), 2, 1) AS steps,
- if(and(isNotNull(latest_1), ifNull(lessOrEquals(latest_1, plus(toTimeZone(latest_0, 'UTC'), toIntervalDay(14))), 0)), dateDiff('second', latest_0, latest_1), NULL) AS step_1_conversion_time
- FROM
- (SELECT aggregation_target AS aggregation_target,
- timestamp AS timestamp,
- step_0 AS step_0,
- latest_0 AS latest_0,
- step_1 AS step_1,
- min(latest_1) OVER (PARTITION BY aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) AS latest_1
- FROM
- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,
- e.`$group_0` AS aggregation_target,
- if(equals(e.event, 'user signed up'), 1, 0) AS step_0,
- if(ifNull(equals(step_0, 1), 0), timestamp, NULL) AS latest_0,
- if(equals(e.event, 'paid'), 1, 0) AS step_1,
- if(ifNull(equals(step_1, 1), 0), timestamp, NULL) AS latest_1
- FROM events AS e
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(toTimeZone(e.timestamp, 'UTC'), toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC')), lessOrEquals(toTimeZone(e.timestamp, 'UTC'), toDateTime64('2020-01-14 23:59:59.999999', 6, 'UTC'))), in(e.event, tuple('paid', 'user signed up')), ifNull(notEquals(nullIf(nullIf(e.`$group_0`, ''), 'null'), ''), 1)), or(ifNull(equals(step_0, 1), 0), ifNull(equals(step_1, 1), 0)))))
- WHERE ifNull(equals(step_0, 1), 0)))
- GROUP BY aggregation_target,
- steps
- HAVING ifNull(equals(steps, max(max_steps)), isNull(steps)
- and isNull(max(max_steps))))
- LIMIT 100 SETTINGS 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=23622320128,
- enable_analyzer=1,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1
- '''
-# ---
-# name: ClickhouseTestFunnelGroups.test_funnel_aggregation_with_groups.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND ((NOT has([''], "$group_0"))
- AND (NOT has([''], "$group_0")))
- AND (step_0 = 1
- OR step_1 = 1) ))
- WHERE step_0 = 1 ))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: ClickhouseTestFunnelGroups.test_funnel_group_aggregation_with_groups_entity_filtering
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT countIf(ifNull(equals(steps, 1), 0)) AS step_1,
- countIf(ifNull(equals(steps, 2), 0)) AS step_2,
- avg(step_1_average_conversion_time_inner) AS step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) AS step_1_median_conversion_time
- FROM
- (SELECT aggregation_target AS aggregation_target,
- steps AS steps,
- avg(step_1_conversion_time) AS step_1_average_conversion_time_inner,
- median(step_1_conversion_time) AS step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target AS aggregation_target,
- steps AS steps,
- max(steps) OVER (PARTITION BY aggregation_target) AS max_steps,
- step_1_conversion_time AS step_1_conversion_time
- FROM
- (SELECT aggregation_target AS aggregation_target,
- timestamp AS timestamp,
- step_0 AS step_0,
- latest_0 AS latest_0,
- step_1 AS step_1,
- latest_1 AS latest_1,
- if(and(ifNull(lessOrEquals(latest_0, latest_1), 0), ifNull(lessOrEquals(latest_1, plus(toTimeZone(latest_0, 'UTC'), toIntervalDay(14))), 0)), 2, 1) AS steps,
- if(and(isNotNull(latest_1), ifNull(lessOrEquals(latest_1, plus(toTimeZone(latest_0, 'UTC'), toIntervalDay(14))), 0)), dateDiff('second', latest_0, latest_1), NULL) AS step_1_conversion_time
- FROM
- (SELECT aggregation_target AS aggregation_target,
- timestamp AS timestamp,
- step_0 AS step_0,
- latest_0 AS latest_0,
- step_1 AS step_1,
- min(latest_1) OVER (PARTITION BY aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) AS latest_1
- FROM
- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,
- e.`$group_0` AS aggregation_target,
- if(and(equals(e.event, 'user signed up'), ifNull(equals(nullIf(nullIf(e.`$group_0`, ''), 'null'), 'org:5'), 0)), 1, 0) AS step_0,
- if(ifNull(equals(step_0, 1), 0), timestamp, NULL) AS latest_0,
- if(equals(e.event, 'paid'), 1, 0) AS step_1,
- if(ifNull(equals(step_1, 1), 0), timestamp, NULL) AS latest_1
- FROM events AS e
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(toTimeZone(e.timestamp, 'UTC'), toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC')), lessOrEquals(toTimeZone(e.timestamp, 'UTC'), toDateTime64('2020-01-14 23:59:59.999999', 6, 'UTC'))), in(e.event, tuple('paid', 'user signed up')), ifNull(notEquals(nullIf(nullIf(e.`$group_0`, ''), 'null'), ''), 1)), or(ifNull(equals(step_0, 1), 0), ifNull(equals(step_1, 1), 0)))))
- WHERE ifNull(equals(step_0, 1), 0)))
- GROUP BY aggregation_target,
- steps
- HAVING ifNull(equals(steps, max(max_steps)), isNull(steps)
- and isNull(max(max_steps))))
- LIMIT 100 SETTINGS 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=23622320128,
- enable_analyzer=1,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1
- '''
-# ---
-# name: ClickhouseTestFunnelGroups.test_funnel_group_aggregation_with_groups_entity_filtering.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up'
- AND (has(['org:5'], "$group_0")), 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND ((NOT has([''], "$group_0"))
- AND (NOT has([''], "$group_0")))
- AND (step_0 = 1
- OR step_1 = 1) ))
- WHERE step_0 = 1 ))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: ClickhouseTestFunnelGroups.test_funnel_with_groups_entity_filtering
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT countIf(ifNull(equals(steps, 1), 0)) AS step_1,
- countIf(ifNull(equals(steps, 2), 0)) AS step_2,
- avg(step_1_average_conversion_time_inner) AS step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) AS step_1_median_conversion_time
- FROM
- (SELECT aggregation_target AS aggregation_target,
- steps AS steps,
- avg(step_1_conversion_time) AS step_1_average_conversion_time_inner,
- median(step_1_conversion_time) AS step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target AS aggregation_target,
- steps AS steps,
- max(steps) OVER (PARTITION BY aggregation_target) AS max_steps,
- step_1_conversion_time AS step_1_conversion_time
- FROM
- (SELECT aggregation_target AS aggregation_target,
- timestamp AS timestamp,
- step_0 AS step_0,
- latest_0 AS latest_0,
- step_1 AS step_1,
- latest_1 AS latest_1,
- if(and(ifNull(lessOrEquals(latest_0, latest_1), 0), ifNull(lessOrEquals(latest_1, plus(toTimeZone(latest_0, 'UTC'), toIntervalDay(14))), 0)), 2, 1) AS steps,
- if(and(isNotNull(latest_1), ifNull(lessOrEquals(latest_1, plus(toTimeZone(latest_0, 'UTC'), toIntervalDay(14))), 0)), dateDiff('second', latest_0, latest_1), NULL) AS step_1_conversion_time
- FROM
- (SELECT aggregation_target AS aggregation_target,
- timestamp AS timestamp,
- step_0 AS step_0,
- latest_0 AS latest_0,
- step_1 AS step_1,
- min(latest_1) OVER (PARTITION BY aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) AS latest_1
- FROM
- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,
- if(and(equals(e.event, 'user signed up'), ifNull(equals(nullIf(nullIf(e.`$group_0`, ''), 'null'), 'org:5'), 0)), 1, 0) AS step_0,
- if(ifNull(equals(step_0, 1), 0), timestamp, NULL) AS latest_0,
- if(equals(e.event, 'paid'), 1, 0) AS step_1,
- if(ifNull(equals(step_1, 1), 0), timestamp, NULL) AS latest_1
- 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 ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(toTimeZone(e.timestamp, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(toTimeZone(e.timestamp, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('paid', 'user signed up'))), or(ifNull(equals(step_0, 1), 0), ifNull(equals(step_1, 1), 0)))))
- WHERE ifNull(equals(step_0, 1), 0)))
- GROUP BY aggregation_target,
- steps
- HAVING ifNull(equals(steps, max(max_steps)), isNull(steps)
- and isNull(max(max_steps))))
- LIMIT 100 SETTINGS 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=23622320128,
- enable_analyzer=1,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1
- '''
-# ---
-# name: ClickhouseTestFunnelGroups.test_funnel_with_groups_entity_filtering.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up'
- AND (has(['org:5'], "$group_0")), 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC') )
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1) ))
- WHERE step_0 = 1 ))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: ClickhouseTestFunnelGroups.test_funnel_with_groups_global_filtering
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT countIf(ifNull(equals(steps, 1), 0)) AS step_1,
- countIf(ifNull(equals(steps, 2), 0)) AS step_2,
- avg(step_1_average_conversion_time_inner) AS step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) AS step_1_median_conversion_time
- FROM
- (SELECT aggregation_target AS aggregation_target,
- steps AS steps,
- avg(step_1_conversion_time) AS step_1_average_conversion_time_inner,
- median(step_1_conversion_time) AS step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target AS aggregation_target,
- steps AS steps,
- max(steps) OVER (PARTITION BY aggregation_target) AS max_steps,
- step_1_conversion_time AS step_1_conversion_time
- FROM
- (SELECT aggregation_target AS aggregation_target,
- timestamp AS timestamp,
- step_0 AS step_0,
- latest_0 AS latest_0,
- step_1 AS step_1,
- latest_1 AS latest_1,
- if(and(ifNull(lessOrEquals(latest_0, latest_1), 0), ifNull(lessOrEquals(latest_1, plus(toTimeZone(latest_0, 'UTC'), toIntervalDay(14))), 0)), 2, 1) AS steps,
- if(and(isNotNull(latest_1), ifNull(lessOrEquals(latest_1, plus(toTimeZone(latest_0, 'UTC'), toIntervalDay(14))), 0)), dateDiff('second', latest_0, latest_1), NULL) AS step_1_conversion_time
- FROM
- (SELECT aggregation_target AS aggregation_target,
- timestamp AS timestamp,
- step_0 AS step_0,
- latest_0 AS latest_0,
- step_1 AS step_1,
- min(latest_1) OVER (PARTITION BY aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) AS latest_1
- FROM
- (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,
- if(equals(e.event, 'user signed up'), 1, 0) AS step_0,
- if(ifNull(equals(step_0, 1), 0), timestamp, NULL) AS latest_0,
- if(equals(e.event, 'paid'), 1, 0) AS step_1,
- if(ifNull(equals(step_1, 1), 0), timestamp, NULL) AS latest_1
- 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 ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT argMax(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(groups.group_properties, 'industry'), ''), 'null'), '^"|"$', ''), toTimeZone(groups._timestamp, 'UTC')) AS properties___industry,
- 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)
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(toTimeZone(e.timestamp, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(toTimeZone(e.timestamp, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('paid', 'user signed up')), ifNull(equals(e__group_0.properties___industry, 'finance'), 0)), or(ifNull(equals(step_0, 1), 0), ifNull(equals(step_1, 1), 0)))))
- WHERE ifNull(equals(step_0, 1), 0)))
- GROUP BY aggregation_target,
- steps
- HAVING ifNull(equals(steps, max(max_steps)), isNull(steps)
- and isNull(max(max_steps))))
- LIMIT 100 SETTINGS 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=23622320128,
- enable_analyzer=1,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1
- '''
-# ---
-# name: ClickhouseTestFunnelGroups.test_funnel_with_groups_global_filtering.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC') )
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (step_0 = 1
- OR step_1 = 1) ))
- WHERE step_0 = 1 ))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
diff --git a/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel_unordered.ambr b/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel_unordered.ambr
deleted file mode 100644
index ca6a7a958682..000000000000
--- a/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel_unordered.ambr
+++ /dev/null
@@ -1,61 +0,0 @@
-# serializer version: 1
-# name: ClickhouseTestUnorderedFunnelGroups.test_unordered_funnel_with_groups
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT sum(step_1) AS step_1,
- sum(step_2) AS step_2,
- arrayMap(x -> if(isNaN(x), NULL, x), [avgArrayOrNull(step_1_conversion_times)])[1] AS step_1_average_conversion_time,
- arrayMap(x -> if(isNaN(x), NULL, x), [medianArrayOrNull(step_1_conversion_times)])[1] AS step_1_median_conversion_time,
- arrayMap(x -> if(isNaN(x), NULL, x), [arrayReduce('median', arrayFlatten(groupArray(arrayFlatten(groupArray(total_conversion_times))) OVER ()))])[1] AS total_median_conversion_time,
- groupArray(row_number) AS row_number,
- final_prop AS final_prop
- FROM
- (SELECT countIf(ifNull(notEquals(bitAnd(steps_bitfield, 1), 0), 1)) AS step_1,
- countIf(ifNull(notEquals(bitAnd(steps_bitfield, 2), 0), 1)) AS step_2,
- groupArrayIf(timings[1], ifNull(greater(timings[1], 0), 0)) AS step_1_conversion_times,
- groupArrayIf(arraySum(timings), ifNull(greaterOrEquals(step_reached, 1), 0)) AS total_conversion_times,
- rowNumberInAllBlocks() AS row_number,
- breakdown AS final_prop
- 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)])))) AS events_array,
- [''] AS prop,
- arrayJoin(aggregate_funnel(2, 1209600, 'first_touch', 'unordered', 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, 'user signed up'), 1, 0) AS step_0,
- if(equals(e.event, 'paid'), 1, 0) AS step_1
- FROM events AS e
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('2020-01-14 23:59:59.999999', 6, 'UTC'))), in(e.event, tuple('paid', 'user signed up')), 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))))
- GROUP BY aggregation_target
- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
- GROUP BY breakdown
- ORDER BY step_2 DESC,
- step_1 DESC)
- GROUP BY final_prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100 SETTINGS 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=23622320128,
- 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_unordered.py b/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_unordered.py
deleted file mode 100644
index 56eaccd227bc..000000000000
--- a/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_unordered.py
+++ /dev/null
@@ -1,95 +0,0 @@
-import json
-from datetime import datetime
-
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
-
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.group.util import create_group
-from posthog.test.test_journeys import journeys_for
-from posthog.test.test_utils import create_group_type_mapping_without_created_at
-
-from ee.api.test.base import LicensedTestMixin
-from ee.clickhouse.views.test.funnel.util import EventPattern, FunnelRequest, get_funnel_ok
-
-
-class ClickhouseTestUnorderedFunnelGroups(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
- maxDiff = None
- CLASS_DATA_LEVEL_SETUP = False
-
- @snapshot_clickhouse_queries
- def test_unordered_funnel_with_groups(self):
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="company", group_type_index=1
- )
-
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:5",
- properties={"industry": "finance"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:6",
- properties={"industry": "technology"},
- )
-
- create_group(
- team_id=self.team.pk,
- group_type_index=1,
- group_key="company:1",
- properties={},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=1,
- group_key="company:2",
- properties={},
- )
-
- events_by_person = {
- "user_1": [
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 1, 3, 14),
- "properties": {"$group_0": "org:5"},
- },
- { # same person, different group, so should count as different step 1 in funnel
- "event": "user signed up",
- "timestamp": datetime(2020, 1, 10, 14),
- "properties": {"$group_0": "org:6"},
- },
- ],
- "user_2": [
- { # different person, same group, so should count as step two in funnel
- "event": "paid",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$group_0": "org:5"},
- }
- ],
- }
- journeys_for(events_by_person, self.team)
-
- params = FunnelRequest(
- events=json.dumps(
- [
- EventPattern(id="user signed up", type="events", order=0),
- EventPattern(id="paid", type="events", order=1),
- ]
- ),
- date_from="2020-01-01",
- date_to="2020-01-14",
- aggregation_group_type_index=0,
- funnel_order_type="unordered",
- insight=INSIGHT_FUNNELS,
- )
-
- result = get_funnel_ok(self.client, self.team.pk, params)
-
- assert result["Completed 1 step"]["count"] == 2
- assert result["Completed 2 steps"]["count"] == 1
- assert result["Completed 2 steps"]["average_conversion_time"] == 86400
diff --git a/ee/clickhouse/views/test/funnel/util.py b/ee/clickhouse/views/test/funnel/util.py
deleted file mode 100644
index d82dc07e7634..000000000000
--- a/ee/clickhouse/views/test/funnel/util.py
+++ /dev/null
@@ -1,44 +0,0 @@
-import dataclasses
-from typing import Any, Literal, Optional, TypedDict, Union
-
-from django.test.client import Client
-
-from posthog.models.property import GroupTypeIndex
-
-
-class EventPattern(TypedDict, total=False):
- id: str
- type: Union[Literal["events"], Literal["actions"]]
- order: int
- properties: dict[str, Any]
-
-
-class FunnelRequest:
- events: str
- date_from: str
- insight: str
- aggregation_group_type_index: Optional[GroupTypeIndex] = None
- date_to: Optional[str] = None
- properties: Optional[str] = None
- funnel_order_type: Optional[str] = None
-
-
-def get_funnel(client: Client, team_id: int, request: FunnelRequest):
- return client.post(
- f"/api/projects/{team_id}/insights/funnel",
- data={key: value for key, value in dataclasses.asdict(request).items() if value is not None},
- )
-
-
-def get_funnel_ok(client: Client, team_id: int, request: FunnelRequest) -> dict[str, Any]:
- response = get_funnel(client=client, team_id=team_id, request=request)
-
- assert response.status_code == 200, response.content
- res = response.json()
- final = {}
-
- for step in res["result"]:
- final[step["name"]] = step
-
- return final
diff --git a/ee/clickhouse/views/test/test_clickhouse_trends.py b/ee/clickhouse/views/test/test_clickhouse_trends.py
deleted file mode 100644
index e35d6748c980..000000000000
--- a/ee/clickhouse/views/test/test_clickhouse_trends.py
+++ /dev/null
@@ -1,1383 +0,0 @@
-import json
-from dataclasses import dataclass, field
-from datetime import datetime
-from typing import Any, Optional, Union
-
-import pytest
-import time_machine
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_person,
- also_test_with_materialized_columns,
- snapshot_clickhouse_queries,
-)
-from unittest.case import skip
-from unittest.mock import ANY
-
-from django.core.cache import cache
-from django.test import Client
-
-from posthog.api.test.test_cohort import create_cohort_ok
-from posthog.api.test.test_event_definition import create_organization, create_team, create_user
-from posthog.models.group.util import create_group
-from posthog.models.instance_setting import set_instance_setting
-from posthog.models.team import Team
-from posthog.test.test_journeys import journeys_for, update_or_create_person
-from posthog.test.test_utils import create_group_type_mapping_without_created_at
-
-from ee.api.test.base import LicensedTestMixin
-
-
-def test_includes_only_intervals_within_range(client: Client):
- """
- This is the case highlighted by https://github.com/PostHog/posthog/issues/2675
-
- Here the issue is that we request, for instance, 14 days as the
- date_from, display at weekly intervals but previously we
- were displaying 4 ticks on the date axis. If we were exactly on the
- beginning of the week for two weeks then we'd want 2 ticks.
- Otherwise we would have 3 ticks as the range would be intersecting
- with three weeks. We should never need to display 4 ticks.
- """
- organization = create_organization(name="test org")
- team = create_team(organization=organization)
- user = create_user("user", "pass", organization)
-
- client.force_login(user)
- cache.clear()
-
- #  I'm creating a cohort here so that I can use as a breakdown, just because
- #  this is what was used demonstrated in
- #  https://github.com/PostHog/posthog/issues/2675 but it might not be the
- #  simplest way to reproduce
-
- # "2021-09-19" is a sunday, i.e. beginning of week
- with time_machine.travel("2021-09-20T16:00:00", tick=False):
- #  First identify as a member of the cohort
- distinct_id = "abc"
- update_or_create_person(
- distinct_ids=[distinct_id],
- team_id=team.id,
- properties={"cohort_identifier": 1},
- )
- cohort = create_cohort_ok(
- client=client,
- team_id=team.id,
- name="test cohort",
- groups=[{"properties": [{"key": "cohort_identifier", "value": "1", "type": "person"}]}],
- )
-
- journeys_for(
- events_by_person={
- distinct_id: [
- {"event": "$pageview", "timestamp": "2021-09-04"},
- {"event": "$pageview", "timestamp": "2021-09-05"},
- {"event": "$pageview", "timestamp": "2021-09-12"},
- {"event": "$pageview", "timestamp": "2021-09-19"},
- ]
- },
- team=team,
- create_people=False,
- )
-
- trends = get_trends_ok(
- client,
- team=team,
- request=TrendsRequestBreakdown(
- date_from="-14days",
- date_to="2021-09-21",
- interval="week",
- insight="TRENDS",
- breakdown=json.dumps([cohort["id"]]),
- breakdown_type="cohort",
- display="ActionsLineGraph",
- events=[
- {
- "id": "$pageview",
- "math": "dau",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- ),
- )
- assert trends == trends | {
- "is_cached": False,
- "last_refresh": "2021-09-20T16:00:00Z",
- "next": None,
- "timezone": "UTC",
- "result": [
- {
- "action": ANY,
- "breakdown_value": cohort["id"],
- "label": "test cohort",
- "count": 2.0,
- "data": [0.0, 1.0, 1.0],
- "labels": ["6–11 Sep", "12–18 Sep", "19–21 Sep"],
- "days": ["2021-09-05", "2021-09-12", "2021-09-19"],
- "filter": ANY,
- "order": 0,
- }
- ],
- }
-
-
-def test_can_specify_number_of_smoothing_intervals(client: Client):
- """
- The Smoothing feature should allow specifying a number of intervals over
- which we will provide smoothing of the aggregated trend data.
- """
- organization = create_organization(name="test org")
- team = create_team(organization=organization)
- user = create_user("user", "pass", organization)
-
- client.force_login(user)
-
- with time_machine.travel("2021-09-20T16:00:00", tick=False):
- journeys_for(
- events_by_person={
- "abc": [
- {"event": "$pageview", "timestamp": "2021-09-01"},
- {"event": "$pageview", "timestamp": "2021-09-01"},
- {"event": "$pageview", "timestamp": "2021-09-02"},
- {"event": "$pageview", "timestamp": "2021-09-03"},
- {"event": "$pageview", "timestamp": "2021-09-03"},
- {"event": "$pageview", "timestamp": "2021-09-03"},
- ]
- },
- team=team,
- )
-
- interval_3_trend = get_trends_ok(
- client,
- team=team,
- request=TrendsRequest(
- date_from="2021-09-01",
- date_to="2021-09-03",
- interval="day",
- insight="TRENDS",
- display="ActionsLineGraph",
- smoothing_intervals=3,
- events=[
- {
- "id": "$pageview",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- }
- ],
- ),
- )
-
- assert interval_3_trend == interval_3_trend | {
- "is_cached": False,
- "last_refresh": "2021-09-20T16:00:00Z",
- "next": None,
- "timezone": "UTC",
- "result": [
- {
- "action": ANY,
- "label": "$pageview",
- "count": 5,
- "data": [2.0, 1, 2.0],
- "labels": ["1-Sep-2021", "2-Sep-2021", "3-Sep-2021"],
- "days": ["2021-09-01", "2021-09-02", "2021-09-03"],
- "filter": ANY,
- "order": 0,
- }
- ],
- }
-
- interval_2_trend = get_trends_ok(
- client,
- team=team,
- request=TrendsRequest(
- date_from="2021-09-01",
- date_to="2021-09-03",
- interval="day",
- insight="TRENDS",
- display="ActionsLineGraph",
- smoothing_intervals=2,
- events=[
- {
- "id": "$pageview",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- }
- ],
- ),
- )
-
- assert interval_2_trend == interval_2_trend | {
- "is_cached": False,
- "last_refresh": "2021-09-20T16:00:00Z",
- "next": None,
- "timezone": "UTC",
- "result": [
- {
- "action": ANY,
- "label": "$pageview",
- "count": 5,
- "data": [2.0, 1, 2.0],
- "labels": ["1-Sep-2021", "2-Sep-2021", "3-Sep-2021"],
- "days": ["2021-09-01", "2021-09-02", "2021-09-03"],
- "filter": ANY,
- "order": 0,
- }
- ],
- }
-
- interval_1_trend = get_trends_ok(
- client,
- team=team,
- request=TrendsRequest(
- date_from="2021-09-01",
- date_to="2021-09-03",
- interval="day",
- insight="TRENDS",
- display="ActionsLineGraph",
- smoothing_intervals=1,
- events=[
- {
- "id": "$pageview",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- }
- ],
- ),
- )
-
- assert interval_1_trend == interval_1_trend | {
- "is_cached": False,
- "last_refresh": "2021-09-20T16:00:00Z",
- "next": None,
- "timezone": "UTC",
- "result": [
- {
- "action": {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "name": "$pageview",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": ANY,
- "properties": {},
- "days": ["2021-09-01T00:00:00Z", "2021-09-02T00:00:00Z", "2021-09-03T00:00:00Z"],
- },
- "label": "$pageview",
- "count": 6.0,
- "data": [2, 1, 3],
- "labels": ["1-Sep-2021", "2-Sep-2021", "3-Sep-2021"],
- "days": ["2021-09-01", "2021-09-02", "2021-09-03"],
- "filter": ANY,
- "order": 0,
- }
- ],
- }
-
-
-def test_smoothing_intervals_copes_with_null_values(client: Client):
- """
- The Smoothing feature should allow specifying a number of intervals over
- which we will provide smoothing of the aggregated trend data.
- """
- organization = create_organization(name="test org")
- team = create_team(organization=organization)
- user = create_user("user", "pass", organization)
-
- client.force_login(user)
- cache.clear()
-
- with time_machine.travel("2021-09-20T16:00:00", tick=False):
- journeys_for(
- events_by_person={
- "abc": [
- {"event": "$pageview", "timestamp": "2021-09-01"},
- {"event": "$pageview", "timestamp": "2021-09-01"},
- {"event": "$pageview", "timestamp": "2021-09-01"},
- # No events on 2 Sept
- {"event": "$pageview", "timestamp": "2021-09-03"},
- {"event": "$pageview", "timestamp": "2021-09-03"},
- {"event": "$pageview", "timestamp": "2021-09-03"},
- ]
- },
- team=team,
- )
-
- interval_3_trend = get_trends_ok(
- client,
- team=team,
- request=TrendsRequest(
- date_from="2021-09-01",
- date_to="2021-09-03",
- interval="day",
- insight="TRENDS",
- display="ActionsLineGraph",
- smoothing_intervals=3,
- events=[
- {
- "id": "$pageview",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- }
- ],
- ),
- )
-
- assert interval_3_trend == interval_3_trend | {
- "is_cached": False,
- "last_refresh": "2021-09-20T16:00:00Z",
- "next": None,
- "timezone": "UTC",
- "result": [
- {
- "action": ANY,
- "label": "$pageview",
- "count": 6.0,
- "data": [3.0, 1.0, 2.0],
- "labels": ["1-Sep-2021", "2-Sep-2021", "3-Sep-2021"],
- "days": ["2021-09-01", "2021-09-02", "2021-09-03"],
- "filter": ANY,
- "order": 0,
- }
- ],
- }
-
- interval_1_trend = get_trends_ok(
- client,
- team=team,
- request=TrendsRequest(
- date_from="2021-09-01",
- date_to="2021-09-03",
- interval="day",
- insight="TRENDS",
- display="ActionsLineGraph",
- smoothing_intervals=1,
- events=[
- {
- "id": "$pageview",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- }
- ],
- ),
- )
-
- assert interval_1_trend == interval_1_trend | {
- "is_cached": False,
- "last_refresh": "2021-09-20T16:00:00Z",
- "next": None,
- "timezone": "UTC",
- "result": [
- {
- "action": ANY,
- "label": "$pageview",
- "count": 6.0,
- "data": [3.0, 0.0, 3.0],
- "labels": ["1-Sep-2021", "2-Sep-2021", "3-Sep-2021"],
- "days": ["2021-09-01", "2021-09-02", "2021-09-03"],
- "filter": ANY,
- "order": 0,
- }
- ],
- }
-
-
-@dataclass
-class TrendsRequest:
- date_from: Optional[str] = None
- date_to: Optional[str] = None
- interval: Optional[str] = None
- insight: Optional[str] = None
- display: Optional[str] = None
- compare: Optional[bool] = None
- events: list[dict[str, Any]] = field(default_factory=list)
- properties: list[dict[str, Any]] = field(default_factory=list)
- smoothing_intervals: Optional[int] = 1
- refresh: Optional[bool] = False
-
-
-@dataclass
-class TrendsRequestBreakdown(TrendsRequest):
- breakdown: Optional[Union[list[int], str]] = None
- breakdown_type: Optional[str] = None
-
-
-def get_trends(client, request: Union[TrendsRequestBreakdown, TrendsRequest], team: Team):
- data: dict[str, Any] = {
- "date_from": request.date_from,
- "date_to": request.date_to,
- "interval": request.interval,
- "insight": request.insight,
- "display": request.display,
- "compare": request.compare,
- "events": json.dumps(request.events),
- "properties": json.dumps(request.properties),
- "smoothing_intervals": request.smoothing_intervals,
- "refresh": request.refresh,
- }
-
- if isinstance(request, TrendsRequestBreakdown):
- data["breakdown"] = request.breakdown
- data["breakdown_type"] = request.breakdown_type
-
- filtered_data = {k: v for k, v in data.items() if v is not None}
-
- return client.get(f"/api/projects/{team.id}/insights/trend/", data=filtered_data)
-
-
-def get_trends_ok(client: Client, request: TrendsRequest, team: Team):
- response = get_trends(client=client, request=request, team=team)
- assert response.status_code == 200, response.content
- return response.json()
-
-
-@dataclass
-class NormalizedTrendResult:
- value: float
- label: str
- breakdown_value: Optional[Union[str, int]]
-
-
-def get_trends_time_series_ok(
- client: Client, request: TrendsRequest, team: Team, with_order: bool = False
-) -> dict[str, dict[str, NormalizedTrendResult]]:
- data = get_trends_ok(client=client, request=request, team=team)
- res = {}
- for item in data["result"]:
- collect_dates = {}
- for idx, date in enumerate(item["days"]):
- collect_dates[date] = NormalizedTrendResult(
- value=item["data"][idx],
- label=item["labels"][idx],
- breakdown_value=item.get("breakdown_value", None),
- )
- suffix = " - {}".format(item["compare_label"]) if item.get("compare_label") else ""
- if with_order:
- suffix += " - {}".format(item["action"]["order"]) if item["action"].get("order") is not None else ""
- res["{}{}".format(item["label"], suffix)] = collect_dates
-
- return res
-
-
-def get_trends_aggregate_ok(client: Client, request: TrendsRequest, team: Team) -> dict[str, NormalizedTrendResult]:
- data = get_trends_ok(client=client, request=request, team=team)
- res = {}
- for item in data["result"]:
- res[item["label"]] = NormalizedTrendResult(
- value=item["aggregated_value"],
- label=item["action"]["name"],
- breakdown_value=item.get("breakdown_value", None),
- )
-
- return res
-
-
-class ClickhouseTestTrends(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
- maxDiff = None
- CLASS_DATA_LEVEL_SETUP = False
-
- @snapshot_clickhouse_queries
- def test_insight_trends_basic(self):
- events_by_person = {
- "1": [{"event": "$pageview", "timestamp": datetime(2012, 1, 14, 3)}],
- "2": [{"event": "$pageview", "timestamp": datetime(2012, 1, 14, 3)}],
- }
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequest(
- date_from="-14d",
- display="ActionsLineGraph",
- events=[
- {
- "id": "$pageview",
- "math": "dau",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- )
- data = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data["$pageview"]["2012-01-13"].value == 0
- assert data["$pageview"]["2012-01-14"].value == 2
- assert data["$pageview"]["2012-01-14"].label == "14-Jan-2012"
- assert data["$pageview"]["2012-01-15"].value == 0
-
- def test_insight_trends_entity_overlap(self):
- events_by_person = {
- "1": [
- {
- "event": "$pageview",
- "timestamp": datetime(2012, 1, 14, 3),
- "properties": {"key": "val"},
- }
- ],
- "2": [{"event": "$pageview", "timestamp": datetime(2012, 1, 14, 3)}],
- "3": [{"event": "$pageview", "timestamp": datetime(2012, 1, 14, 3)}],
- }
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequest(
- date_from="-14d",
- display="ActionsLineGraph",
- events=[
- {
- "id": "$pageview",
- "math": "dau",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- },
- {
- "id": "$pageview",
- "math": "dau",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 1,
- "properties": [{"key": "key", "value": "val"}],
- "math_property": None,
- },
- ],
- )
- data = get_trends_time_series_ok(self.client, request, self.team, with_order=True)
-
- assert data["$pageview - 0"]["2012-01-13"].value == 0
- assert data["$pageview - 0"]["2012-01-14"].value == 3
- assert data["$pageview - 1"]["2012-01-14"].value == 1
- assert data["$pageview - 0"]["2012-01-14"].label == "14-Jan-2012"
- assert data["$pageview - 0"]["2012-01-15"].value == 0
-
- @snapshot_clickhouse_queries
- def test_insight_trends_aggregate(self):
- events_by_person = {
- "1": [{"event": "$pageview", "timestamp": datetime(2012, 1, 13, 3)}],
- "2": [{"event": "$pageview", "timestamp": datetime(2012, 1, 14, 3)}],
- }
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequest(
- date_from="-14d",
- display="ActionsPie",
- events=[
- {
- "id": "$pageview",
- "math": None,
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- )
- data = get_trends_aggregate_ok(self.client, request, self.team)
-
- assert data["$pageview"].value == 2
- assert data["$pageview"].label == "$pageview"
-
- @snapshot_clickhouse_queries
- def test_insight_trends_cumulative(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"key": "some_val"})
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"key": "some_val"})
- _create_person(team_id=self.team.pk, distinct_ids=["p3"], properties={"key": "some_val"})
-
- events_by_person = {
- "p1": [
- {
- "event": "$pageview",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "val"},
- },
- {
- "event": "$pageview",
- "timestamp": datetime(2012, 1, 14, 3),
- "properties": {"key": "val"},
- },
- ],
- "p2": [
- {
- "event": "$pageview",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "notval"},
- }
- ],
- "p3": [
- {
- "event": "$pageview",
- "timestamp": datetime(2012, 1, 14, 3),
- "properties": {"key": "val"},
- }
- ],
- }
- journeys_for(events_by_person, self.team, create_people=False)
-
- # Total Volume
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequest(
- date_from="-14d",
- display="ActionsLineGraphCumulative",
- events=[
- {
- "id": "$pageview",
- "math": None,
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- )
- data_response = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data_response["$pageview"]["2012-01-13"].value == 2
- assert data_response["$pageview"]["2012-01-14"].value == 4
- assert data_response["$pageview"]["2012-01-15"].value == 4
- assert data_response["$pageview"]["2012-01-14"].label == "14-Jan-2012"
-
- # DAU
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequest(
- date_from="-14d",
- display="ActionsLineGraphCumulative",
- events=[
- {
- "id": "$pageview",
- "math": "dau",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- )
- data_response = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data_response["$pageview"]["2012-01-13"].value == 2
- assert data_response["$pageview"]["2012-01-14"].value == 3
- assert data_response["$pageview"]["2012-01-15"].value == 3
- assert data_response["$pageview"]["2012-01-14"].label == "14-Jan-2012"
-
- # breakdown
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequestBreakdown(
- date_from="-14d",
- display="ActionsLineGraphCumulative",
- breakdown="key",
- breakdown_type="event",
- events=[
- {
- "id": "$pageview",
- "math": None,
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- )
- data_response = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data_response["val"]["2012-01-13"].value == 1
- assert data_response["val"]["2012-01-13"].breakdown_value == "val"
- assert data_response["val"]["2012-01-14"].value == 3
- assert data_response["val"]["2012-01-14"].label == "14-Jan-2012"
-
- # breakdown wau
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequestBreakdown(
- date_from="-14d",
- display="ActionsLineGraphCumulative",
- breakdown="key",
- breakdown_type="event",
- events=[
- {
- "id": "$pageview",
- "math": "weekly_active",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [{"type": "person", "key": "key", "value": "some_val"}],
- "math_property": None,
- }
- ],
- properties=[{"type": "person", "key": "key", "value": "some_val"}],
- )
- data_response = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data_response["val"]["2012-01-13"].value == 1
- assert data_response["val"]["2012-01-13"].breakdown_value == "val"
- assert data_response["val"]["2012-01-14"].value == 3
- assert data_response["val"]["2012-01-14"].label == "14-Jan-2012"
-
- # breakdown dau
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequestBreakdown(
- date_from="-14d",
- display="ActionsLineGraphCumulative",
- breakdown="key",
- breakdown_type="event",
- events=[
- {
- "id": "$pageview",
- "math": "dau",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- )
- data_response = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data_response["val"]["2012-01-13"].value == 1
- assert data_response["val"]["2012-01-13"].breakdown_value == "val"
- assert data_response["val"]["2012-01-14"].value == 2
- assert data_response["val"]["2012-01-14"].label == "14-Jan-2012"
-
- @also_test_with_materialized_columns(["key"])
- def test_breakdown_with_filter(self):
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "val"},
- }
- ],
- "person2": [
- {
- "event": "sign up",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "oh"},
- }
- ],
- }
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- params = TrendsRequestBreakdown(
- date_from="-14d",
- breakdown="key",
- events=[{"id": "sign up", "name": "sign up", "type": "events", "order": 0}],
- properties=[{"key": "key", "value": "oh", "operator": "not_icontains"}],
- )
- data_response = get_trends_time_series_ok(self.client, params, self.team)
-
- assert data_response["val"]["2012-01-13"].value == 1
- assert data_response["val"]["2012-01-13"].breakdown_value == "val"
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- params = TrendsRequestBreakdown(
- date_from="-14d",
- breakdown="key",
- display="ActionsPie",
- events=[{"id": "sign up", "name": "sign up", "type": "events", "order": 0}],
- )
- aggregate_response = get_trends_aggregate_ok(self.client, params, self.team)
-
- assert aggregate_response["val"].value == 1
-
- def test_insight_trends_compare(self):
- events_by_person = {
- "p1": [
- {
- "event": "$pageview",
- "timestamp": datetime(2012, 1, 5, 3),
- "properties": {"key": "val"},
- },
- {
- "event": "$pageview",
- "timestamp": datetime(2012, 1, 14, 3),
- "properties": {"key": "val"},
- },
- ],
- "p2": [
- {
- "event": "$pageview",
- "timestamp": datetime(2012, 1, 5, 3),
- "properties": {"key": "notval"},
- },
- {
- "event": "$pageview",
- "timestamp": datetime(2012, 1, 14, 3),
- "properties": {"key": "notval"},
- },
- ],
- }
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequest(
- date_from="-7d",
- compare=True,
- events=[
- {
- "id": "$pageview",
- "name": "$pageview",
- "type": "events",
- "order": 0,
- }
- ],
- )
- data_response = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data_response["$pageview - current"]["2012-01-13"].value == 0
- assert data_response["$pageview - current"]["2012-01-14"].value == 2
-
- assert data_response["$pageview - previous"]["2012-01-04"].value == 0
- assert data_response["$pageview - previous"]["2012-01-05"].value == 2
-
-
-class ClickhouseTestTrendsGroups(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
- maxDiff = None
- CLASS_DATA_LEVEL_SETUP = False
-
- def _create_groups(self):
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="company", group_type_index=1
- )
-
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:5",
- properties={"industry": "finance"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:6",
- properties={"industry": "technology"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:7",
- properties={"industry": "finance"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=1,
- group_key="company:10",
- properties={"industry": "finance"},
- )
-
- @snapshot_clickhouse_queries
- def test_aggregating_by_group(self):
- self._create_groups()
-
- events_by_person = {
- "person1": [
- {
- "event": "$pageview",
- "timestamp": datetime(2020, 1, 2, 12),
- "properties": {"$group_0": "org:5"},
- },
- {
- "event": "$pageview",
- "timestamp": datetime(2020, 1, 2, 12),
- "properties": {"$group_0": "org:6"},
- },
- {
- "event": "$pageview",
- "timestamp": datetime(2020, 1, 2, 12),
- "properties": {"$group_0": "org:6", "$group_1": "company:10"},
- },
- ]
- }
- journeys_for(events_by_person, self.team)
-
- request = TrendsRequest(
- date_from="2020-01-01 00:00:00",
- date_to="2020-01-12 00:00:00",
- events=[
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "math": "unique_group",
- "math_group_type_index": 0,
- }
- ],
- )
- data_response = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data_response["$pageview"]["2020-01-01"].value == 0
- assert data_response["$pageview"]["2020-01-02"].value == 2
-
- @snapshot_clickhouse_queries
- def test_aggregating_by_session(self):
- events_by_person = {
- "person1": [
- {
- "event": "$pageview",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$session_id": "1"},
- },
- {
- "event": "$pageview",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$session_id": "1"},
- },
- {
- "event": "$pageview",
- "timestamp": datetime(2020, 1, 2, 12),
- "properties": {"$session_id": "2"},
- },
- ],
- "person2": [
- {
- "event": "$pageview",
- "timestamp": datetime(2020, 1, 2, 12),
- "properties": {"$session_id": "3"},
- }
- ],
- }
- journeys_for(events_by_person, self.team)
-
- request = TrendsRequest(
- date_from="2020-01-01 00:00:00",
- date_to="2020-01-12 00:00:00",
- events=[
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "math": "unique_session",
- }
- ],
- )
- data_response = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data_response["$pageview"]["2020-01-01"].value == 1
- assert data_response["$pageview"]["2020-01-02"].value == 2
-
-
-class ClickhouseTestTrendsCaching(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
- maxDiff = None
- CLASS_DATA_LEVEL_SETUP = False
-
- @snapshot_clickhouse_queries
- def test_insight_trends_merging(self):
- set_instance_setting("STRICT_CACHING_TEAMS", "all")
-
- events_by_person = {
- "1": [{"event": "$pageview", "timestamp": datetime(2012, 1, 13, 3)}],
- "2": [{"event": "$pageview", "timestamp": datetime(2012, 1, 13, 3)}],
- }
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequest(
- date_from="-14d",
- display="ActionsLineGraph",
- events=[
- {
- "id": "$pageview",
- "math": "dau",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- )
- data = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data["$pageview"]["2012-01-13"].value == 2
- assert data["$pageview"]["2012-01-14"].value == 0
- assert data["$pageview"]["2012-01-15"].value == 0
-
- events_by_person = {"1": [{"event": "$pageview", "timestamp": datetime(2012, 1, 15, 3)}]}
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequest(
- date_from="-14d",
- display="ActionsLineGraph",
- events=[
- {
- "id": "$pageview",
- "math": "dau",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- refresh=True,
- )
- data = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data["$pageview"]["2012-01-13"].value == 2
- assert data["$pageview"]["2012-01-14"].value == 0
- assert data["$pageview"]["2012-01-15"].value == 1
-
- @skip("Don't handle breakdowns right now")
- def test_insight_trends_merging_breakdown(self):
- set_instance_setting("STRICT_CACHING_TEAMS", "all")
-
- events_by_person = {
- "1": [
- {
- "event": "$action",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "1"},
- },
- {
- "event": "$action",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "2"},
- },
- ],
- "2": [
- {
- "event": "$action",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "1"},
- }
- ],
- }
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequestBreakdown(
- date_from="-14d",
- display="ActionsLineGraph",
- events=[
- {
- "id": "$action",
- "math": "dau",
- "name": "$action",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- breakdown="key",
- )
- data = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data["$action - 1"]["2012-01-13"].value == 2
- assert data["$action - 1"]["2012-01-14"].value == 0
- assert data["$action - 1"]["2012-01-15"].value == 0
-
- assert data["$action - 2"]["2012-01-13"].value == 1
- assert data["$action - 2"]["2012-01-14"].value == 0
- assert data["$action - 2"]["2012-01-15"].value == 0
-
- events_by_person = {
- "1": [
- {
- "event": "$action",
- "timestamp": datetime(2012, 1, 15, 3),
- "properties": {"key": "2"},
- }
- ],
- "2": [
- {
- "event": "$action",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "2"},
- }
- ], # this won't be counted
- }
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequestBreakdown(
- date_from="-14d",
- display="ActionsLineGraph",
- events=[
- {
- "id": "$action",
- "math": "dau",
- "name": "$action",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- breakdown="key",
- refresh=True,
- )
- data = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data["$action - 1"]["2012-01-13"].value == 2
- assert data["$action - 1"]["2012-01-14"].value == 0
- assert data["$action - 1"]["2012-01-15"].value == 0
-
- assert data["$action - 2"]["2012-01-13"].value == 1
- assert data["$action - 2"]["2012-01-14"].value == 0
- assert data["$action - 2"]["2012-01-15"].value == 1
-
- @skip("Don't handle breakdowns right now")
- def test_insight_trends_merging_breakdown_multiple(self):
- set_instance_setting("STRICT_CACHING_TEAMS", "all")
-
- events_by_person = {
- "1": [
- {
- "event": "$pageview",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "1"},
- },
- {
- "event": "$action",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "1"},
- },
- {
- "event": "$action",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "2"},
- },
- ],
- "2": [
- {
- "event": "$pageview",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "1"},
- },
- {
- "event": "$action",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "1"},
- },
- ],
- }
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequestBreakdown(
- date_from="-14d",
- display="ActionsLineGraph",
- events=[
- {
- "id": "$pageview",
- "math": "dau",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- },
- {
- "id": "$action",
- "math": "dau",
- "name": "$action",
- "custom_name": None,
- "type": "events",
- "order": 1,
- "properties": [],
- "math_property": None,
- },
- ],
- breakdown="key",
- )
- data = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data["$pageview - 1"]["2012-01-13"].value == 2
- assert data["$pageview - 1"]["2012-01-14"].value == 0
- assert data["$pageview - 1"]["2012-01-15"].value == 0
-
- assert data["$action - 1"]["2012-01-13"].value == 2
- assert data["$action - 1"]["2012-01-14"].value == 0
- assert data["$action - 1"]["2012-01-15"].value == 0
-
- assert data["$action - 2"]["2012-01-13"].value == 1
- assert data["$action - 2"]["2012-01-14"].value == 0
- assert data["$action - 2"]["2012-01-15"].value == 0
-
- events_by_person = {
- "1": [
- {
- "event": "$pageview",
- "timestamp": datetime(2012, 1, 15, 3),
- "properties": {"key": "1"},
- },
- {
- "event": "$action",
- "timestamp": datetime(2012, 1, 15, 3),
- "properties": {"key": "2"},
- },
- ],
- "2": [
- {
- "event": "$action",
- "timestamp": datetime(2012, 1, 13, 3),
- "properties": {"key": "2"},
- } # this won't be counted
- ],
- }
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- request = TrendsRequestBreakdown(
- date_from="-14d",
- display="ActionsLineGraph",
- events=[
- {
- "id": "$pageview",
- "math": "dau",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- },
- {
- "id": "$action",
- "math": "dau",
- "name": "$action",
- "custom_name": None,
- "type": "events",
- "order": 1,
- "properties": [],
- "math_property": None,
- },
- ],
- breakdown="key",
- refresh=True,
- )
- data = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data["$pageview - 1"]["2012-01-13"].value == 2
- assert data["$pageview - 1"]["2012-01-14"].value == 0
- assert data["$pageview - 1"]["2012-01-15"].value == 1
-
- assert data["$action - 1"]["2012-01-13"].value == 2
- assert data["$action - 1"]["2012-01-14"].value == 0
- assert data["$action - 1"]["2012-01-15"].value == 0
-
- assert data["$action - 2"]["2012-01-13"].value == 1
- assert data["$action - 2"]["2012-01-14"].value == 0
- assert data["$action - 2"]["2012-01-15"].value == 1
-
- # When the latest time interval in the cached result doesn't match the current interval, do not use caching pattern
- @snapshot_clickhouse_queries
- def test_insight_trends_merging_skipped_interval(self):
- set_instance_setting("STRICT_CACHING_TEAMS", "all")
-
- events_by_person = {
- "1": [{"event": "$pageview", "timestamp": datetime(2012, 1, 13, 3)}],
- "2": [{"event": "$pageview", "timestamp": datetime(2012, 1, 13, 3)}],
- }
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-14T04:01:34.000Z", tick=False):
- request = TrendsRequest(
- date_from="-14d",
- display="ActionsLineGraph",
- events=[
- {
- "id": "$pageview",
- "math": "dau",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- )
- data = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data["$pageview"]["2012-01-13"].value == 2
- assert data["$pageview"]["2012-01-14"].value == 0
-
- events_by_person = {
- "1": [{"event": "$pageview", "timestamp": datetime(2012, 1, 15, 3)}],
- "2": [{"event": "$pageview", "timestamp": datetime(2012, 1, 16, 3)}],
- }
- journeys_for(events_by_person, self.team)
-
- with time_machine.travel("2012-01-16T04:01:34.000Z", tick=False):
- request = TrendsRequest(
- date_from="-14d",
- display="ActionsLineGraph",
- events=[
- {
- "id": "$pageview",
- "math": "dau",
- "name": "$pageview",
- "custom_name": None,
- "type": "events",
- "order": 0,
- "properties": [],
- "math_property": None,
- }
- ],
- refresh=True,
- )
- data = get_trends_time_series_ok(self.client, request, self.team)
-
- assert data["$pageview"]["2012-01-13"].value == 2
- assert data["$pageview"]["2012-01-14"].value == 0
- assert data["$pageview"]["2012-01-15"].value == 1
- assert data["$pageview"]["2012-01-16"].value == 1
diff --git a/posthog/api/query_coalescer.py b/posthog/api/query_coalescer.py
index b81808404731..1d38085da668 100644
--- a/posthog/api/query_coalescer.py
+++ b/posthog/api/query_coalescer.py
@@ -267,8 +267,6 @@ _TEAM_ID_RE = re.compile(r"^/api/(?:environments|projects)/(\d+)/")
_COALESCE_PATH_PATTERNS = [
re.compile(r"^/api/(?:environments|projects)/\d+/query/$"),
- re.compile(r"^/api/(?:environments|projects)/\d+/insights/trend/$"), # legacy endpoint
- re.compile(r"^/api/(?:environments|projects)/\d+/insights/funnel/$"), # legacy endpoint
re.compile(r"^/api/(?:environments|projects)/\d+/insights/\d+/$"),
]
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index f06b15adb7b7..7e1f5843a707 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -2468,18 +2468,6 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
dashboard_json = self.dashboard_api.get_dashboard(dashboard.pk)
self.assertEqual(len(dashboard_json["tiles"][0]["insight"]["result"][0]["days"]), 2)
- def test_invalid_properties(self):
- properties = "invalid_json"
-
- response = self.client.get(f"/api/projects/{self.team.id}/insights/trend/?properties={properties}")
-
- self.assertEqual(response.status_code, 400, response.content)
- self.assertDictEqual(
- response.json(),
- self.validation_error_response("Properties are unparsable!", "invalid_input"),
- response.content,
- )
-
def test_insights_with_no_insight_set(self):
# We were saving some insights on the default dashboard with no insight
dashboard = Dashboard.objects.create(team=self.team, name="Dashboard", created_by=self.user)
diff --git a/posthog/api/test/test_query_coalescing.py b/posthog/api/test/test_query_coalescing.py
index be7524d76657..fef56970f235 100644
--- a/posthog/api/test/test_query_coalescing.py
+++ b/posthog/api/test/test_query_coalescing.py
@@ -478,8 +478,6 @@ class TestQueryCoalescingMiddleware(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand(
[
("query", "/api/environments/{team_id}/query/"),
- ("insights_trend", "/api/environments/{team_id}/insights/trend/"),
- ("insights_funnel", "/api/environments/{team_id}/insights/funnel/"),
("insights_pk", "/api/environments/{team_id}/insights/123/"),
]
)
diff --git a/products/exports/backend/tasks/csv_exporter.py b/products/exports/backend/tasks/csv_exporter.py
index 250e4ca88e0a..f419938fb083 100644
--- a/products/exports/backend/tasks/csv_exporter.py
+++ b/products/exports/backend/tasks/csv_exporter.py
@@ -453,7 +453,9 @@ def get_from_insights_api(exported_asset: ExportedAsset, limit: int, resource: d
# The underlying resource (e.g. a cohort) can be deleted or become unresolvable
# mid-export, which surfaces as a 404 partway through pagination. Treat that as
# end-of-data and return what we have rather than failing the whole export.
- if e.response is not None and e.response.status_code == 404:
+ # A 404 on the first page is a different thing: the path never resolved, so
+ # there is nothing to return and an empty file would read as a successful export.
+ if e.response is not None and e.response.status_code == 404 and total > 0:
logger.warning(
"csv_exporter.resource_gone",
exc=e,
diff --git a/products/exports/backend/tasks/test/test_csv_exporter.py b/products/exports/backend/tasks/test/test_csv_exporter.py
index b3e0c27d4694..ef5d70b622a0 100644
--- a/products/exports/backend/tasks/test/test_csv_exporter.py
+++ b/products/exports/backend/tasks/test/test_csv_exporter.py
@@ -468,6 +468,22 @@ class TestCSVExporter(APIBaseTest):
assert exported_asset.content is not None
assert b"abc" in exported_asset.content
+ @patch("products.exports.backend.tasks.csv_exporter.logger")
+ def test_404_on_the_first_page_raises(self, _mock_logger: MagicMock) -> None:
+ # A stored path that no longer resolves 404s before any row is fetched. Breaking
+ # there would publish an empty file as a successful export.
+ with patch("products.exports.backend.tasks.csv_exporter.make_api_call") as patched_make_api_call:
+ exported_asset = self._create_asset()
+
+ not_found_error = HTTPError("404 Client Error") # type: ignore[call-arg]
+ not_found_error.response = Mock()
+ not_found_error.response.status_code = 404
+ not_found_error.response.text = "Not found."
+ patched_make_api_call.side_effect = not_found_error
+
+ with pytest.raises(HTTPError):
+ csv_exporter.export_tabular(exported_asset)
+
@patch("products.exports.backend.tasks.csv_exporter.logger")
def test_non_404_http_error_still_raises(self, _mock_logger: MagicMock) -> None:
with patch("products.exports.backend.tasks.csv_exporter.make_api_call") as patched_make_api_call:
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index 5d592eb7986c..40b5c88ffa10 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -1,18 +1,14 @@
import json
-import logging
from collections.abc import Sequence
from datetime import datetime, timedelta
from functools import lru_cache
from typing import Any, Union, cast
from django.conf import settings
-from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.db.models import Count, F, Max, QuerySet
from django.db.models.query_utils import Q
-from django.http import HttpResponse
from django.utils.functional import SimpleLazyObject
-from django.utils.text import slugify
from django.utils.timezone import now
import structlog
@@ -38,9 +34,7 @@ from rest_framework_csv import renderers as csvrenderers
from posthog.schema import ProductKey, QueryStatus
-from posthog.hogql.constants import BREAKDOWN_VALUES_LIMIT
from posthog.hogql.errors import ExposedHogQLError
-from posthog.hogql.timings import HogQLTimings
from posthog import schema
from posthog.api.documentation import extend_schema, extend_schema_field, extend_schema_serializer
@@ -50,11 +44,11 @@ from posthog.api.monitoring import Feature, monitor
from posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_param
from posthog.api.query_coalescer import QueryCoalescingMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.services.query import process_query_dict, process_query_model
+from posthog.api.services.query import process_query_model
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
from posthog.api.sharing_publish_gate import blocked_access_for_user, is_publicly_shared
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
-from posthog.api.utils import action, format_paginated_url
+from posthog.api.utils import action
from posthog.auth import (
PersonalAPIKeyAuthentication,
SessionAuthentication,
@@ -70,7 +64,6 @@ from posthog.errors import ExposedCHQueryError
from posthog.event_usage import EventSource, get_event_source, get_request_analytics_properties, report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
-from posthog.helpers.multi_property_breakdown import protect_old_clients_from_multi_property_default
from posthog.helpers.trigram_search import (
DESCRIPTION_FIELD,
MAX_SEARCH_LENGTH,
@@ -86,12 +79,10 @@ from posthog.hogql_queries.apply_dashboard_filters import (
resolve_effective_dashboard_filters,
resolve_filter_layers_by_priority,
)
-from posthog.hogql_queries.legacy_compatibility.feature_flag import get_query_method
-from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query
-from posthog.hogql_queries.query_runner import BLOCKING_EXECUTION_MODES, ExecutionMode, execution_mode_from_refresh
+from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.hogql_queries.refresh_policy import ComputeSurface, resolve_execution_mode
from posthog.kafka_client.topics import KAFKA_METRICS_TIME_TO_SEE_DATA
-from posthog.models import Filter, User
+from posthog.models import User
from posthog.models.activity_logging.activity_log import (
Change,
Detail,
@@ -103,12 +94,10 @@ from posthog.models.activity_logging.activity_log import (
log_activity,
)
from posthog.models.activity_logging.activity_page import ActivityLogPaginatedResponseSerializer, activity_page_response
-from posthog.models.filters.utils import get_filter
from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.models.utils import UUIDT
from posthog.permissions import TeamMemberStrictManagementPermission
-from posthog.ph_client import feature_enabled_or_false
from posthog.query_cache import QueryCache
from posthog.rate_limit import (
AIObservabilitySummarizationBurstThrottle,
@@ -121,7 +110,7 @@ from posthog.renderers import SafeJSONRenderer
from posthog.resource_limits import LimitKey, check_count_limit
from posthog.schema_migrations.upgrade import upgrade
from posthog.schema_migrations.upgrade_manager import upgrade_insight
-from posthog.settings import CAPTURE_TIME_TO_SEE_DATA, SITE_URL
+from posthog.settings import CAPTURE_TIME_TO_SEE_DATA
from posthog.shared_link_user import SharedLinkUser
from posthog.user_permissions import UserPermissionsSerializerMixin
from posthog.utils import (
@@ -134,10 +123,7 @@ from posthog.utils import (
variables_override_requested_by_client,
)
-from products.access_control.backend.facade.user_access_control import (
- UserAccessControlError,
- access_level_satisfied_for_resource,
-)
+from products.access_control.backend.facade.user_access_control import access_level_satisfied_for_resource
from products.access_control.backend.presentation.access_control import (
AccessControlViewSetMixin,
UserAccessControlSerializerMixin,
@@ -195,8 +181,6 @@ from common.hogvm.python.utils import HogVMException
logger = structlog.get_logger(__name__)
tracer = trace.get_tracer(__name__)
-LEGACY_INSIGHT_ENDPOINTS_BLOCKED_FLAG = "legacy-insight-endpoints-disabled"
-
EXPORT_QUERY_CACHE_MISS = Counter(
"export_query_cache_miss",
@@ -260,52 +244,6 @@ def log_and_report_insight_activity(
)
-def is_legacy_insight_endpoint_blocked(user: Any, team: Team) -> bool:
- distinct_id = getattr(user, "distinct_id", None)
- if not distinct_id:
- return False
-
- return feature_enabled_or_false(
- LEGACY_INSIGHT_ENDPOINTS_BLOCKED_FLAG,
- str(distinct_id),
- groups={
- "organization": str(team.organization_id),
- "project": str(team.id),
- },
- group_properties={
- "organization": {"id": str(team.organization_id)},
- "project": {"id": str(team.id)},
- },
- send_feature_flag_events=False,
- )
-
-
-def capture_legacy_api_call(request: request.Request, team: Team) -> None:
- if is_legacy_insight_endpoint_blocked(request.user, team):
- raise PermissionDenied("Legacy insight endpoints are not available for this user.")
-
- try:
- properties = {
- "path": request._request.path,
- "method": request._request.method,
- "query_method": get_query_method(request=request, team=team),
- "filter": get_filter(request=request, team=team),
- "user_agent": request.headers.get("user-agent"),
- }
-
- report_user_action(
- request.user,
- "legacy insight endpoint called",
- properties,
- team=team,
- organization=team.organization,
- request=request,
- )
- except Exception as e:
- logging.exception(f"Error in capture_legacy_api_call: {e}")
- pass
-
-
class QuerySchemaParser(JSONParser):
"""
A query schema parser that only parses the query field and validates it against the schema if it is present
@@ -2392,132 +2330,6 @@ When set, the specified dashboard's filters and date range override will be appl
return Response({"name": metadata.name, "description": metadata.description})
- def _run_legacy_query(
- self,
- request: request.Request,
- filter_overrides: dict[str, Any] | None = None,
- ) -> dict[str, Any]:
- """Convert Filter-style params to a query and run via process_query_dict.
-
- Uses the unified QueryRunner cache instead of the removed legacy filter-based cache.
- """
- team = self.team
- filter = Filter(request=request, team=team)
- if filter_overrides:
- filter = filter.shallow_clone(overrides=filter_overrides)
-
- query_dict = filter_to_query(filter.to_dict()).model_dump()
-
- refresh = refresh_requested_by_client(request)
- if refresh:
- execution_mode = execution_mode_from_refresh(refresh)
- else:
- execution_mode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
-
- # Legacy endpoints never supported async — restrict to blocking modes
- if execution_mode not in BLOCKING_EXECUTION_MODES:
- execution_mode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
-
- query_response = process_query_dict(
- team,
- query_dict,
- execution_mode=execution_mode,
- user=request.user if isinstance(request.user, User) else None,
- analytics_props=get_request_analytics_properties(request),
- )
-
- if isinstance(query_response, BaseModel):
- return {
- "result": getattr(query_response, "results", []),
- "timezone": getattr(query_response, "timezone", team.timezone),
- "is_cached": getattr(query_response, "is_cached", False),
- "last_refresh": getattr(query_response, "last_refresh", None),
- }
- return {
- "result": query_response.get("results", query_response.get("result", [])),
- "timezone": query_response.get("timezone", team.timezone),
- "is_cached": query_response.get("is_cached", False),
- "last_refresh": query_response.get("last_refresh", None),
- }
-
- @extend_schema(exclude=True)
- @action(methods=["GET", "POST"], detail=False, required_scopes=["insight:read"])
- def trend(self, request: request.Request, *args: Any, **kwargs: Any):
- capture_legacy_api_call(request, self.team)
-
- timings = HogQLTimings()
- try:
- with timings.measure("calculate"):
- result = self._run_legacy_query(request)
- except (ExposedHogQLError, ExposedCHQueryError, HogVMException) as e:
- raise ValidationError(str(e), getattr(e, "code_name", None))
- except UserAccessControlError as e:
- raise ValidationError(str(e))
- except ObjectDoesNotExist as e:
- # The legacy filter path resolves cohort and action ids while building the query, and a
- # dangling id surfaces as that model's DoesNotExist. The request is what is wrong, so it
- # is a 400 rather than a 500.
- raise ValidationError(str(e))
-
- filter = Filter(request=request, team=self.team)
-
- params_breakdown_limit = request.GET.get("breakdown_limit")
- if params_breakdown_limit is not None and params_breakdown_limit != "":
- breakdown_values_limit = int(params_breakdown_limit)
- else:
- breakdown_values_limit = BREAKDOWN_VALUES_LIMIT
-
- next = (
- format_paginated_url(request, filter.offset, breakdown_values_limit)
- if len(result["result"]) >= breakdown_values_limit
- else None
- )
- if self.request.accepted_renderer.format == "csv":
- csvexport = []
- for item in result["result"]:
- line = {"series": (item["action"].get("custom_name") if item["action"] else None) or item["label"]}
- for index, data in enumerate(item["data"]):
- line[item["labels"][index]] = data
- csvexport.append(line)
- renderer = csvrenderers.CSVRenderer()
- renderer.header = csvexport[0].keys()
- export = renderer.render(csvexport)
- if request.GET.get("export_insight_id"):
- export = "{}/insights/{}/\n".format(SITE_URL, request.GET["export_insight_id"]).encode() + export
-
- response = HttpResponse(export)
- response["Content-Disposition"] = (
- 'attachment; filename="{name} ({date_from} {date_to}) from PostHog.csv"'.format(
- name=slugify(request.GET.get("export_name", "export")),
- date_from=filter.date_from.strftime("%Y-%m-%d -") if filter.date_from else "up until",
- date_to=filter.date_to.strftime("%Y-%m-%d"),
- )
- )
- return response
-
- result["timings"] = [val.model_dump() for val in timings.to_list()]
-
- return Response({**result, "next": next})
-
- @extend_schema(exclude=True)
- @action(methods=["GET", "POST"], detail=False, required_scopes=["insight:read"])
- def funnel(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:
- capture_legacy_api_call(request, self.team)
-
- timings = HogQLTimings()
- try:
- with timings.measure("calculate"):
- funnel = self._run_legacy_query(request, filter_overrides={"insight": "FUNNELS"})
- except (ExposedHogQLError, ExposedCHQueryError, HogVMException) as e:
- raise ValidationError(str(e), getattr(e, "code_name", None))
-
- if isinstance(funnel["result"], BaseModel):
- funnel["result"] = funnel["result"].model_dump()
- funnel["result"] = protect_old_clients_from_multi_property_default(request.data, funnel["result"])
- funnel["timings"] = [val.model_dump() for val in timings.to_list()]
-
- return Response(funnel)
-
# ******************************************
# /projects/:id/insights/viewed
# Creates or updates InsightViewed objects for the user/insight combo(s)
@@ -2949,7 +2761,3 @@ When set, the specified dashboard's filters and date range override will be appl
)
return Response(status=status.HTTP_201_CREATED)
-
-
-class LegacyInsightViewSet(InsightViewSet):
- param_derived_from_user_current_team = "project_id"
diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
index d8ba42b96d84..25050d9aecad 100644
--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
@@ -1,350 +1,4 @@
# serializer version: 1
-# name: TestInsight.test_insight_funnels_hogql_breakdown
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT sum(step_1) AS step_1,
- sum(step_2) AS step_2,
- arrayMap(x -> if(isNaN(x), NULL, x), [avgArrayOrNull(step_1_conversion_times)])[1] AS step_1_average_conversion_time,
- arrayMap(x -> if(isNaN(x), NULL, x), [medianArrayOrNull(step_1_conversion_times)])[1] AS step_1_median_conversion_time,
- arrayMap(x -> if(isNaN(x), NULL, x), [arrayReduce('median', arrayFlatten(groupArray(arrayFlatten(groupArray(total_conversion_times))) OVER ()))])[1] AS total_median_conversion_time,
- groupArray(row_number) AS row_number,
- final_prop AS final_prop
- FROM
- (SELECT countIf(ifNull(notEquals(bitAnd(steps_bitfield, 1), 0), 1)) AS step_1,
- countIf(ifNull(notEquals(bitAnd(steps_bitfield, 2), 0), 1)) AS step_2,
- groupArrayIf(timings[1], ifNull(greater(timings[1], 0), 0)) AS step_1_conversion_times,
- groupArrayIf(arraySum(timings), ifNull(greaterOrEquals(step_reached, 1), 0)) AS total_conversion_times,
- rowNumberInAllBlocks() AS row_number,
- breakdown AS final_prop
- FROM
- (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, arrayMap(x -> ifNull(x, ''), prop_basic), arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1)])))) AS events_array,
- argMinIf(prop_basic, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_basic))) AS prop,
- arrayJoin(aggregate_funnel_array(2, 1209600, 'first_touch', 'ordered', [if(empty(prop), [''], 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,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,
- e.uuid AS uuid,
- e.`$session_id` AS `$session_id`,
- e.`$window_id` AS `$window_id`,
- if(equals(e.event, 'user signed up'), 1, 0) AS step_0,
- if(equals(e.event, 'user did things'), 1, 0) AS step_1,
- ([replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', '')] AS value) AS prop_basic,
- prop_basic AS prop
- 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)
- 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('user did things', 'user signed up')), ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0)), or(equals(step_0, 1), equals(step_1, 1))))
- GROUP BY aggregation_target
- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
- GROUP BY breakdown
- ORDER BY step_2 DESC,
- step_1 DESC)
- GROUP BY final_prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100 SETTINGS 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=23622320128,
- 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: TestInsight.test_insight_funnels_hogql_global_filters
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT sum(step_1) AS step_1,
- sum(step_2) AS step_2,
- arrayMap(x -> if(isNaN(x), NULL, x), [avgArrayOrNull(step_1_conversion_times)])[1] AS step_1_average_conversion_time,
- arrayMap(x -> if(isNaN(x), NULL, x), [medianArrayOrNull(step_1_conversion_times)])[1] AS step_1_median_conversion_time,
- arrayMap(x -> if(isNaN(x), NULL, x), [arrayReduce('median', arrayFlatten(groupArray(arrayFlatten(groupArray(total_conversion_times))) OVER ()))])[1] AS total_median_conversion_time,
- groupArray(row_number) AS row_number,
- final_prop AS final_prop
- FROM
- (SELECT countIf(ifNull(notEquals(bitAnd(steps_bitfield, 1), 0), 1)) AS step_1,
- countIf(ifNull(notEquals(bitAnd(steps_bitfield, 2), 0), 1)) AS step_2,
- groupArrayIf(timings[1], ifNull(greater(timings[1], 0), 0)) AS step_1_conversion_times,
- groupArrayIf(arraySum(timings), ifNull(greaterOrEquals(step_reached, 1), 0)) AS total_conversion_times,
- rowNumberInAllBlocks() AS row_number,
- breakdown AS final_prop
- 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)])))) AS events_array,
- [''] AS prop,
- arrayJoin(aggregate_funnel(2, 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,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,
- e.uuid AS uuid,
- e.`$session_id` AS `$session_id`,
- e.`$window_id` AS `$window_id`,
- if(equals(e.event, 'user signed up'), 1, 0) AS step_0,
- if(equals(e.event, 'user did things'), 1, 0) AS step_1
- 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)
- 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('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
- GROUP BY aggregation_target
- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
- GROUP BY breakdown
- ORDER BY step_2 DESC,
- step_1 DESC)
- GROUP BY final_prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100 SETTINGS 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=23622320128,
- 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: TestInsight.test_insight_funnels_hogql_local_filters
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT sum(step_1) AS step_1,
- sum(step_2) AS step_2,
- arrayMap(x -> if(isNaN(x), NULL, x), [avgArrayOrNull(step_1_conversion_times)])[1] AS step_1_average_conversion_time,
- arrayMap(x -> if(isNaN(x), NULL, x), [medianArrayOrNull(step_1_conversion_times)])[1] AS step_1_median_conversion_time,
- arrayMap(x -> if(isNaN(x), NULL, x), [arrayReduce('median', arrayFlatten(groupArray(arrayFlatten(groupArray(total_conversion_times))) OVER ()))])[1] AS total_median_conversion_time,
- groupArray(row_number) AS row_number,
- final_prop AS final_prop
- FROM
- (SELECT countIf(ifNull(notEquals(bitAnd(steps_bitfield, 1), 0), 1)) AS step_1,
- countIf(ifNull(notEquals(bitAnd(steps_bitfield, 2), 0), 1)) AS step_2,
- groupArrayIf(timings[1], ifNull(greater(timings[1], 0), 0)) AS step_1_conversion_times,
- groupArrayIf(arraySum(timings), ifNull(greaterOrEquals(step_reached, 1), 0)) AS total_conversion_times,
- rowNumberInAllBlocks() AS row_number,
- breakdown AS final_prop
- 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)])))) AS events_array,
- [''] AS prop,
- arrayJoin(aggregate_funnel(2, 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,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,
- e.uuid AS uuid,
- e.`$session_id` AS `$session_id`,
- e.`$window_id` AS `$window_id`,
- if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_0,
- if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_1
- 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)
- 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('user did things', 'user signed up'))), or(equals(step_0, 1), equals(step_1, 1))))
- GROUP BY aggregation_target
- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
- GROUP BY breakdown
- ORDER BY step_2 DESC,
- step_1 DESC)
- GROUP BY final_prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100 SETTINGS 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=23622320128,
- 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: TestInsight.test_insight_trend_hogql_breakdown
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT groupArray(1)(date)[1] AS date,
- arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,
- if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value
- FROM
- (SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total,
- breakdown_value AS breakdown_value,
- rowNumberInAllBlocks() AS row_number
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start,
- breakdown_value AS breakdown_value
- FROM
- (SELECT count() AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start,
- ifNull(nullIf(leftUTF8(toString(if(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), 'le%ss', 'more')), 400), ''), '$$_posthog_breakdown_null_$$') AS breakdown_value
- FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- GROUP BY day_start,
- breakdown_value)
- GROUP BY day_start,
- breakdown_value
- ORDER BY day_start ASC,
- breakdown_value ASC)
- GROUP BY breakdown_value
- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)
- WHERE isNotNull(breakdown_value)
- GROUP BY breakdown_value
- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC
- LIMIT 50000 SETTINGS 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: TestInsight.test_insight_trend_hogql_global_filters
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start
- FROM
- (SELECT count() AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
- FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
- GROUP BY day_start)
- GROUP BY day_start
- ORDER BY day_start ASC)
- ORDER BY arraySum(total) DESC
- LIMIT 50000 SETTINGS 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: TestInsight.test_insight_trend_hogql_global_filters.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start
- FROM
- (SELECT count() AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
- FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
- GROUP BY day_start)
- GROUP BY day_start
- ORDER BY day_start ASC)
- ORDER BY arraySum(total) DESC
- LIMIT 50000 SETTINGS 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: TestInsight.test_insight_trend_hogql_local_filters
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start
- FROM
- (SELECT count() AS total,
- toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
- FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
- GROUP BY day_start)
- GROUP BY day_start
- ORDER BY day_start ASC)
- ORDER BY arraySum(total) DESC
- LIMIT 50000 SETTINGS 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: TestInsight.test_listing_insights_does_not_nplus1
'''
SELECT "posthog_user"."id",
diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight_funnels.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight_funnels.ambr
deleted file mode 100644
index 7fa617956bbf..000000000000
--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight_funnels.ambr
+++ /dev/null
@@ -1,199 +0,0 @@
-# serializer version: 1
-# name: ClickhouseTestFunnelTypes.test_funnel_time_to_convert_auto_bins
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT bin_from_seconds,
- person_count,
- arrayAvg(timings) AS averageConversionTime,
- arrayMap(x -> if(isNaN(x), NULL, x), [arrayReduce('median', timings)])[1] AS medianConversionTime
- FROM
- (SELECT timings AS timings,
- accurateCastOrNull(least(60, greatest(1, ceil(cbrt(ifNull(length(timings), 0))))), 'Int64') AS bin_count,
- floor(arrayMin(timings)) AS min_timing,
- ceil(arrayMax(timings)) AS max_timing,
- ceil(divide(minus(max_timing, min_timing), bin_count)) AS bin_width_seconds_raw,
- if(ifNull(greater(bin_width_seconds_raw, 0), 0), bin_width_seconds_raw, 60) AS bin_width_seconds,
- arrayMap(n -> accurateCastOrNull(round(plus(min_timing, multiply(n, bin_width_seconds))), 'Int64'), range(0, plus(bin_count, 1))) AS buckets,
- arrayMap(timing -> accurateCastOrNull(floor(divide(minus(timing, min_timing), bin_width_seconds)), 'Int64'), timings) AS indices,
- arrayMap(x -> countEqual(indices, minus(x, 1)), range(1, plus(bin_count, 2))) AS counts
- FROM
- (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timings
- 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,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) 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)
- 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'))), 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 ifNull(greaterOrEquals(step_reached, 1), 0))) ARRAY
- JOIN counts AS person_count,
- buckets AS bin_from_seconds
- LIMIT 100 SETTINGS 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=23622320128,
- 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: ClickhouseTestFunnelTypes.test_funnel_time_to_convert_auto_bins_strict
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT bin_from_seconds,
- person_count,
- arrayAvg(timings) AS averageConversionTime,
- arrayMap(x -> if(isNaN(x), NULL, x), [arrayReduce('median', timings)])[1] AS medianConversionTime
- FROM
- (SELECT timings AS timings,
- accurateCastOrNull(least(60, greatest(1, ceil(cbrt(ifNull(length(timings), 0))))), 'Int64') AS bin_count,
- floor(arrayMin(timings)) AS min_timing,
- ceil(arrayMax(timings)) AS max_timing,
- ceil(divide(minus(max_timing, min_timing), bin_count)) AS bin_width_seconds_raw,
- if(ifNull(greater(bin_width_seconds_raw, 0), 0), bin_width_seconds_raw, 60) AS bin_width_seconds,
- arrayMap(n -> accurateCastOrNull(round(plus(min_timing, multiply(n, bin_width_seconds))), 'Int64'), range(0, plus(bin_count, 1))) AS buckets,
- arrayMap(timing -> accurateCastOrNull(floor(divide(minus(timing, min_timing), bin_width_seconds)), 'Int64'), timings) AS indices,
- arrayMap(x -> countEqual(indices, minus(x, 1)), range(1, plus(bin_count, 2))) AS counts
- FROM
- (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timings
- 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', 'strict', 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,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) 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)
- WHERE and(equals(e.team_id, 99999), and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))))
- GROUP BY aggregation_target
- HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
- WHERE ifNull(greaterOrEquals(step_reached, 1), 0))) ARRAY
- JOIN counts AS person_count,
- buckets AS bin_from_seconds
- LIMIT 100 SETTINGS 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=23622320128,
- 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: ClickhouseTestFunnelTypes.test_funnel_time_to_convert_auto_bins_unordered
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT bin_from_seconds,
- person_count,
- arrayAvg(timings) AS averageConversionTime,
- arrayMap(x -> if(isNaN(x), NULL, x), [arrayReduce('median', timings)])[1] AS medianConversionTime
- FROM
- (SELECT timings AS timings,
- accurateCastOrNull(least(60, greatest(1, ceil(cbrt(ifNull(length(timings), 0))))), 'Int64') AS bin_count,
- floor(arrayMin(timings)) AS min_timing,
- ceil(arrayMax(timings)) AS max_timing,
- ceil(divide(minus(max_timing, min_timing), bin_count)) AS bin_width_seconds_raw,
- if(ifNull(greater(bin_width_seconds_raw, 0), 0), bin_width_seconds_raw, 60) AS bin_width_seconds,
- arrayMap(n -> accurateCastOrNull(round(plus(min_timing, multiply(n, bin_width_seconds))), 'Int64'), range(0, plus(bin_count, 1))) AS buckets,
- arrayMap(timing -> accurateCastOrNull(floor(divide(minus(timing, min_timing), bin_width_seconds)), 'Int64'), timings) AS indices,
- arrayMap(x -> countEqual(indices, minus(x, 1)), range(1, plus(bin_count, 2))) AS counts
- FROM
- (SELECT groupArray(arraySum(arraySlice(timings, 1, 1))) AS timings
- 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', 'unordered', 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,
- if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) 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)
- 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'))), 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 ifNull(greaterOrEquals(step_reached, 1), 0))) ARRAY
- JOIN counts AS person_count,
- buckets AS bin_from_seconds
- LIMIT 100 SETTINGS 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=23622320128,
- 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/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.py
index c6e5ac9da151..6c558a02e548 100644
--- a/products/product_analytics/backend/tests/api/test_insight.py
+++ b/products/product_analytics/backend/tests/api/test_insight.py
@@ -10,9 +10,7 @@ from posthog.test.base import (
QueryMatchingTest,
_create_event,
_create_person,
- also_test_with_materialized_columns,
flush_persons_and_events,
- snapshot_clickhouse_queries,
snapshot_postgres_queries,
)
from unittest import mock
@@ -56,11 +54,9 @@ from posthog.models import Filter, OrganizationMembership, SharingConfiguration,
from posthog.models.project import Project
from posthog.test.db_context_capturing import capture_db_queries
from posthog.test.insight_queries import default_pageview_query, insight_query
-from posthog.test.persons import create_person
from products.access_control.backend.models.access_control import AccessControl
from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold
-from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.facade.access import DashboardAccessMethod
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text
@@ -90,25 +86,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
super().setUp()
self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
- @parameterized.expand(
- [
- ("trend", "/api/projects/{team_id}/insights/trend/"),
- ("funnel", "/api/projects/{team_id}/insights/funnel/"),
- ]
- )
- def test_legacy_insight_endpoints_blocked_with_feature_flag(self, _name: str, path: str) -> None:
- with patch(
- "products.product_analytics.backend.presentation.insight.feature_enabled_or_false", return_value=True
- ) as mock_feature_enabled:
- response = self.client.get(path.format(team_id=self.team.id))
-
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- self.assertEqual(response.json()["detail"], "Legacy insight endpoints are not available for this user.")
- legacy_calls = [
- c for c in mock_feature_enabled.call_args_list if c[0][0] == "legacy-insight-endpoints-disabled"
- ]
- self.assertEqual(len(legacy_calls), 1)
-
def test_creating_insight_with_legacy_filters_is_rejected(self) -> None:
response = self.client.post(
f"/api/projects/{self.team.id}/insights/",
@@ -2289,172 +2266,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["query"]["source"]["after"], "-180d")
- # BASIC TESTING OF ENDPOINTS. /queries as in depth testing for each insight
-
- def test_insight_trends_basic(self) -> None:
- with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
- _create_event(team=self.team, event="$pageview", distinct_id="1")
- _create_event(team=self.team, event="$pageview", distinct_id="2")
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- response = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/?events={json.dumps([{'id': '$pageview'}])}"
- ).json()
-
- self.assertEqual(response["result"][0]["count"], 2)
- self.assertEqual(response["result"][0]["action"]["name"], "$pageview")
- self.assertEqual(response["timezone"], "UTC")
-
- def test_nonexistent_cohort_is_handled(self) -> None:
- response = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/?events={json.dumps([{'id': '$pageview'}])}&properties={json.dumps([{'type': 'cohort', 'key': 'id', 'value': 2137}])}"
- )
-
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())
-
- def test_cohort_without_match_group_works(self) -> None:
- whatever_cohort_without_match_groups = Cohort.objects.create(team=self.team)
-
- response_nonexistent_property = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/?events={json.dumps([{'id': '$pageview'}])}&properties={json.dumps([{'type': 'event', 'key': 'foo', 'value': 'barabarab'}])}"
- )
- response_cohort_without_match_groups = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/?events={json.dumps([{'id': '$pageview'}])}&properties={json.dumps([{'type': 'cohort', 'key': 'id', 'value': whatever_cohort_without_match_groups.pk}])}"
- ) # This should not throw an error, just act like there's no event matches
-
- self.assertEqual(response_nonexistent_property.status_code, 200)
- response_nonexistent_property_data = response_nonexistent_property.json()
- response_cohort_without_match_groups_data = response_cohort_without_match_groups.json()
- response_nonexistent_property_data.pop("last_refresh")
- response_cohort_without_match_groups_data.pop("last_refresh")
- self.assertEntityResponseEqual(
- response_nonexistent_property_data["result"],
- response_cohort_without_match_groups_data["result"],
- ) # Both cases just empty
-
- def test_precalculated_cohort_works(self) -> None:
- _create_person(team=self.team, distinct_ids=["person_1"], properties={"foo": "bar"})
-
- whatever_cohort: Cohort = Cohort.objects.create(
- id=113,
- team=self.team,
- groups=[
- {
- "properties": [
- {
- "type": "person",
- "key": "foo",
- "value": "bar",
- "operator": "exact",
- }
- ]
- }
- ],
- last_calculation=timezone.now(),
- )
-
- whatever_cohort.calculate_people_ch(pending_version=0)
-
- with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True): # Normally this is False in tests
- response_user_property = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/?events={json.dumps([{'id': '$pageview'}])}&properties={json.dumps([{'type': 'person', 'key': 'foo', 'value': 'bar'}])}"
- )
- response_precalculated_cohort = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/?events={json.dumps([{'id': '$pageview'}])}&properties={json.dumps([{'type': 'cohort', 'key': 'id', 'value': 113}])}"
- )
-
- self.assertEqual(response_precalculated_cohort.status_code, 200)
- response_user_property_data = response_user_property.json()
- response_precalculated_cohort_data = response_precalculated_cohort.json()
- response_user_property_data.pop("last_refresh")
- response_precalculated_cohort_data.pop("last_refresh")
-
- self.assertEntityResponseEqual(
- response_user_property_data["result"],
- response_precalculated_cohort_data["result"],
- )
-
- def test_insight_trends_compare(self) -> None:
- with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
- for i in range(25):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="1",
- properties={"$some_property": f"value{i}"},
- )
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- response = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/",
- data={"events": json.dumps([{"id": "$pageview"}]), "compare": "true"},
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- result = response.json()
- self.assertEqual(len(result["result"]), 2)
- self.assertEqual(result["result"][0]["compare_label"], "current")
- self.assertEqual(result["result"][1]["compare_label"], "previous")
-
- def test_insight_trends_breakdown_pagination(self) -> None:
- with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
- for i in range(25):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="1",
- properties={"$some_property": f"value{i}"},
- )
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- response = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/",
- data={
- "events": json.dumps([{"id": "$pageview"}]),
- "breakdown": "$some_property",
- "breakdown_type": "event",
- },
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
- self.assertIn("offset=25", response.json()["next"])
-
- def test_insight_funnels_basic_post(self) -> None:
- _create_person(team=self.team, distinct_ids=["1"])
- _create_event(team=self.team, event="user signed up", distinct_id="1")
- _create_event(team=self.team, event="user did things", distinct_id="1")
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "user did things", "type": "events", "order": 1},
- ],
- "funnel_window_days": 14,
- },
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- response_json = response.json()
- # clickhouse funnels don't have a loading system
- self.assertEqual(len(response_json["result"]), 2)
- self.assertEqual(response_json["result"][0]["name"], "user signed up")
- self.assertEqual(response_json["result"][0]["count"], 1)
- self.assertEqual(response_json["result"][1]["name"], "user did things")
- self.assertEqual(response_json["result"][1]["count"], 1)
-
- # Tests backwards-compatibility when we changed GET to POST | GET
- def test_insight_funnels_basic_get(self) -> None:
- _create_event(team=self.team, event="user signed up", distinct_id="1")
- _create_event(team=self.team, event="user did things", distinct_id="1")
- response = self.client.get(
- f"/api/projects/{self.team.id}/insights/funnel/?funnel_window_days=14&events={json.dumps([{'id': 'user signed up', 'type': 'events', 'order': 0}, {'id': 'user did things', 'type': 'events', 'order': 1}])}"
- ).json()
-
- # clickhouse funnels don't have a loading system
- self.assertEqual(len(response["result"]), 2)
- self.assertEqual(response["result"][0]["name"], "user signed up")
- self.assertEqual(response["result"][1]["name"], "user did things")
- self.assertEqual(response["timezone"], "UTC")
-
def test_logged_out_user_cannot_retrieve_insight(self) -> None:
self.client.logout()
insight = Insight.objects.create(
@@ -2747,36 +2558,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
self.assertEqual(response_correct_token_list.json()["count"], 0)
- def test_insight_trends_csv(self) -> None:
- with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
- _create_event(team=self.team, event="$pageview", distinct_id="1")
- _create_event(team=self.team, event="$pageview", distinct_id="2")
-
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- _create_event(team=self.team, event="$pageview", distinct_id="2")
- response = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend.csv/?events={json.dumps([{'id': '$pageview', 'custom_name': 'test custom'}])}&export_name=Pageview count&export_insight_id=test123"
- )
-
- lines = response.content.splitlines()
-
- self.assertEqual(lines[0], b"http://localhost:8010/insights/test123/", lines[0])
- self.assertEqual(
- lines[1],
- b"series,8-Jan-2012,9-Jan-2012,10-Jan-2012,11-Jan-2012,12-Jan-2012,13-Jan-2012,14-Jan-2012,15-Jan-2012",
- lines[0],
- )
- self.assertEqual(lines[2], b"test custom,0,0,0,0,0,0,2,1")
- self.assertEqual(len(lines), 3, response.content)
-
- def _create_one_person_cohort(self, properties: list[dict[str, Any]]) -> int:
- create_person(team=self.team, properties=properties)
- cohort_one_id = self.client.post(
- f"/api/projects/{self.team.id}/cohorts",
- data={"name": "whatever", "groups": [{"properties": properties}]},
- ).json()["id"]
- return cohort_one_id
-
@parameterized.expand([("single_id", 1), ("bulk_ids", 3)])
@time_machine.travel("2022-03-22T00:00:00.000Z", tick=False)
def test_create_insight_viewed(self, _name: str, count: int) -> None:
@@ -3367,21 +3148,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
self.assertEqual(response.status_code, 201, response.content)
- def test_including_query_id_does_not_affect_cache_key(self) -> None:
- """
- regression test, by introducing a query_id we were changing the cache key
- so, if you made the same query twice, the second one would not be cached, only because the query id had changed
- """
- self._get_insight_with_client_query_id("b3ef3987-b8e7-4339-b9b8-fa2b65606692")
- response = self._get_insight_with_client_query_id("00000000-b8e7-4339-b9b8-fa2b65606692")
-
- # Second call should hit cache since client_query_id is not part of the cache key
- assert response.get("is_cached") is True
-
- def _get_insight_with_client_query_id(self, client_query_id: str) -> dict:
- query_params = f"?events={json.dumps([{'id': '$pageview'}])}&client_query_id={client_query_id}"
- return self.client.get(f"/api/projects/{self.team.id}/insights/trend/{query_params}").json()
-
def assert_insight_activity(self, insight_id: Optional[int], expected: list[dict]):
activity_response = self.dashboard_api.get_insight_activity(insight_id)
@@ -3394,580 +3160,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.maxDiff = None
assert activity == expected
- @also_test_with_materialized_columns(event_properties=["int_value"], person_properties=["fish"])
- @snapshot_clickhouse_queries
- def test_insight_trend_hogql_global_filters(self) -> None:
- _create_person(team=self.team, distinct_ids=["1"], properties={"fish": "there is no fish"})
- with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
- for i in range(25):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="1",
- properties={"int_value": i},
- )
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- # 25 events total
- response = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/",
- data={"events": json.dumps([{"id": "$pageview"}])},
- )
- found_data_points = response.json()["result"][0]["count"]
- self.assertEqual(found_data_points, 25)
-
- # test trends global property filter
- response = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/",
- data={
- "events": json.dumps([{"id": "$pageview"}]),
- "properties": json.dumps(
- [
- {
- "key": "toInt(properties.int_value) > 10 and 'bla' != 'a%sd'",
- "type": "hogql",
- },
- {
- "key": "like(person.properties.fish, '%fish%')",
- "type": "hogql",
- },
- ]
- ),
- },
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
- found_data_points = response.json()["result"][0]["count"]
- self.assertEqual(found_data_points, 14)
-
- # test trends global property filter with a disallowed placeholder
- response_placeholder = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/",
- data={
- "events": json.dumps([{"id": "$pageview"}]),
- "properties": json.dumps(
- [
- {"key": "{team_id} * 5", "type": "hogql"},
- ]
- ),
- },
- )
- self.assertEqual(
- response_placeholder.status_code,
- status.HTTP_400_BAD_REQUEST,
- response_placeholder.json(),
- )
- self.assertEqual(
- response_placeholder.json(),
- self.validation_error_response("Unresolved placeholder: {team_id}", code="hogql_query_error"),
- )
-
- @also_test_with_materialized_columns(event_properties=["int_value"], person_properties=["fish"])
- @snapshot_clickhouse_queries
- def test_insight_trend_hogql_local_filters(self) -> None:
- _create_person(team=self.team, distinct_ids=["1"], properties={"fish": "there is no fish"})
- with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
- for i in range(25):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="1",
- properties={"int_value": i},
- )
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- # test trends local property filter
- response = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/",
- data={
- "events": json.dumps(
- [
- {
- "id": "$pageview",
- "properties": json.dumps(
- [
- {
- "key": "toInt(properties.int_value) < 10 and 'bla' != 'a%sd'",
- "type": "hogql",
- },
- {
- "key": "like(person.properties.fish, '%fish%')",
- "type": "hogql",
- },
- ]
- ),
- }
- ]
- )
- },
- )
- found_data_points = response.json()["result"][0]["count"]
- self.assertEqual(found_data_points, 10)
-
- @also_test_with_materialized_columns(event_properties=["int_value"], person_properties=["fish"])
- @snapshot_clickhouse_queries
- def test_insight_trend_hogql_breakdown(self) -> None:
- _create_person(team=self.team, distinct_ids=["1"], properties={"fish": "there is no fish"})
- with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
- for i in range(25):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="1",
- properties={"int_value": i},
- )
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- # test trends breakdown
- response = self.client.get(
- f"/api/projects/{self.team.id}/insights/trend/",
- data={
- "events": json.dumps([{"id": "$pageview"}]),
- "breakdown_type": "hogql",
- "breakdown": "if(toInt(properties.int_value) < 10, 'le%ss', 'more')",
- },
- )
- result = response.json()["result"]
- self.assertEqual(result[0]["count"], 15)
- self.assertEqual(result[0]["breakdown_value"], "more")
- self.assertEqual(result[1]["count"], 10)
- self.assertEqual(result[1]["breakdown_value"], "le%ss")
-
- @snapshot_clickhouse_queries
- @also_test_with_materialized_columns(event_properties=["int_value"], person_properties=["fish"])
- def test_insight_funnels_hogql_global_filters(self) -> None:
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- _create_person(
- team=self.team,
- distinct_ids=["1"],
- properties={"fish": "there is no fish"},
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="1",
- properties={"int_value": 1},
- )
- _create_event(
- team=self.team,
- event="user did things",
- distinct_id="1",
- properties={"int_value": 20},
- )
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "user did things", "type": "events", "order": 1},
- ],
- "properties": json.dumps(
- [
- {
- "key": "toInt(properties.int_value) < 10 and 'bla' != 'a%sd'",
- "type": "hogql",
- },
- {
- "key": "like(person.properties.fish, '%fish%')",
- "type": "hogql",
- },
- ]
- ),
- "funnel_window_days": 14,
- },
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- response_json = response.json()
- self.assertEqual(len(response_json["result"]), 2)
- self.assertEqual(response_json["result"][0]["name"], "user signed up")
- self.assertEqual(response_json["result"][0]["count"], 1)
- self.assertEqual(response_json["result"][1]["name"], "user did things")
- self.assertEqual(response_json["result"][1]["count"], 0)
- self.assertEqual(response_json["timezone"], "UTC")
-
- @snapshot_clickhouse_queries
- @also_test_with_materialized_columns(event_properties=["int_value"], person_properties=["fish"])
- def test_insight_funnels_hogql_local_filters(self) -> None:
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- _create_person(
- team=self.team,
- distinct_ids=["1"],
- properties={"fish": "there is no fish"},
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="1",
- properties={"int_value": 1},
- )
- _create_event(
- team=self.team,
- event="user did things",
- distinct_id="1",
- properties={"int_value": 20},
- )
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "properties": json.dumps(
- [
- {
- "key": "toInt(properties.int_value) < 10 and 'bla' != 'a%sd'",
- "type": "hogql",
- },
- {
- "key": "like(person.properties.fish, '%fish%')",
- "type": "hogql",
- },
- ]
- ),
- },
- {
- "id": "user did things",
- "type": "events",
- "order": 1,
- "properties": json.dumps(
- [
- {
- "key": "toInt(properties.int_value) < 10 and 'bla' != 'a%sd'",
- "type": "hogql",
- },
- {
- "key": "like(person.properties.fish, '%fish%')",
- "type": "hogql",
- },
- ]
- ),
- },
- ],
- "funnel_window_days": 14,
- },
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- response_json = response.json()
- self.assertEqual(len(response_json["result"]), 2)
- self.assertEqual(response_json["result"][0]["name"], "user signed up")
- self.assertEqual(response_json["result"][0]["count"], 1)
- self.assertEqual(response_json["result"][1]["name"], "user did things")
- self.assertEqual(response_json["result"][1]["count"], 0)
- self.assertEqual(response_json["timezone"], "UTC")
-
- @snapshot_clickhouse_queries
- @also_test_with_materialized_columns(event_properties=["int_value"], person_properties=["fish"])
- def test_insight_funnels_hogql_breakdown(self) -> None:
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- _create_person(
- team=self.team,
- distinct_ids=["1"],
- properties={"fish": "there is no fish"},
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="1",
- properties={"int_value": 1},
- )
- _create_event(
- team=self.team,
- event="user did things",
- distinct_id="1",
- properties={"int_value": 20},
- )
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "breakdown_type": "hogql",
- "breakdowns": [{"property": "person.properties.fish", "type": "hogql"}],
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "user did things", "type": "events", "order": 1},
- ],
- "properties": json.dumps(
- [
- {
- "key": "toInt(properties.int_value) < 10 and 'bla' != 'a%sd'",
- "type": "hogql",
- },
- ]
- ),
- "funnel_window_days": 14,
- },
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
- response_json = response.json()
- self.assertEqual(len(response_json["result"]), 1)
- self.assertEqual(len(response_json["result"][0]), 2)
- self.assertEqual(response_json["result"][0][0]["name"], "user signed up")
- self.assertEqual(response_json["result"][0][0]["count"], 1)
- self.assertEqual(response_json["result"][0][0]["breakdown"], ["there is no fish"])
- self.assertEqual(response_json["result"][0][0]["breakdown_value"], ["there is no fish"])
- self.assertEqual(response_json["result"][0][1]["name"], "user did things")
- self.assertEqual(response_json["result"][0][1]["count"], 0)
- self.assertEqual(response_json["result"][0][1]["breakdown"], ["there is no fish"])
- self.assertEqual(response_json["result"][0][1]["breakdown_value"], ["there is no fish"])
- self.assertEqual(response_json["timezone"], "UTC")
-
- # @snapshot_clickhouse_queries
- @also_test_with_materialized_columns(event_properties=["int_value"], person_properties=["fish"])
- def test_insight_funnels_hogql_breakdown_single(self) -> None:
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- _create_person(
- team=self.team,
- distinct_ids=["1"],
- properties={"fish": "there is no fish"},
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="1",
- properties={"int_value": 1},
- )
- _create_event(
- team=self.team,
- event="user did things",
- distinct_id="1",
- properties={"int_value": 20},
- )
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "breakdown_type": "hogql",
- "breakdown": "person.properties.fish",
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "user did things", "type": "events", "order": 1},
- ],
- "properties": json.dumps(
- [
- {
- "key": "toInt(properties.int_value) < 10 and 'bla' != 'a%sd'",
- "type": "hogql",
- },
- ]
- ),
- "funnel_window_days": 14,
- },
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
- response_json = response.json()
- self.assertEqual(len(response_json["result"]), 1)
- self.assertEqual(len(response_json["result"][0]), 2)
- self.assertEqual(response_json["result"][0][0]["name"], "user signed up")
- self.assertEqual(response_json["result"][0][0]["count"], 1)
- self.assertEqual(response_json["result"][0][0]["breakdown"], ["there is no fish"])
- self.assertEqual(response_json["result"][0][0]["breakdown_value"], ["there is no fish"])
- self.assertEqual(response_json["result"][0][1]["name"], "user did things")
- self.assertEqual(response_json["result"][0][1]["count"], 0)
- self.assertEqual(response_json["result"][0][1]["breakdown"], ["there is no fish"])
- self.assertEqual(response_json["result"][0][1]["breakdown_value"], ["there is no fish"])
- self.assertEqual(response_json["timezone"], "UTC")
-
- def test_insight_funnels_hogql_aggregating_steps(self) -> None:
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- _create_person(team=self.team, distinct_ids=["1"], properties={"int_value": 1})
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="1",
- properties={"$browser": "Chrome"},
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="1",
- properties={"$browser": "Firefox"},
- )
- _create_event(
- team=self.team,
- event="user did things",
- distinct_id="1",
- properties={"$browser": "Chrome"},
- )
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "insight": "FUNNELS",
- "entity_type": "events",
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "math": "total",
- },
- {
- "id": "user did things",
- "type": "events",
- "order": 1,
- "math": "total",
- },
- ],
- "properties": json.dumps(
- [
- {
- "key": "toInt(person.properties.int_value) < 10 and 'bla' != 'a%sd'",
- "type": "hogql",
- },
- ]
- ),
- "funnel_aggregate_by_hogql": "properties.$browser",
- "funnel_viz_type": "steps",
- },
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- response_json = response.json()
- self.assertEqual(len(response_json["result"]), 2)
- self.assertEqual(response_json["result"][0]["name"], "user signed up")
- self.assertEqual(response_json["result"][0]["count"], 2)
- self.assertEqual(response_json["result"][1]["name"], "user did things")
- self.assertEqual(response_json["result"][1]["count"], 1)
- self.assertEqual(response_json["timezone"], "UTC")
-
- @skip("Compatibility issue CH 23.12 (see #21318)")
- def test_insight_funnels_hogql_aggregating_time_to_convert(self) -> None:
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- _create_person(team=self.team, distinct_ids=["1"], properties={"int_value": 1})
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="1",
- properties={"$browser": "Chrome"},
- )
- with time_machine.travel("2012-01-15T04:01:36.500Z", tick=False):
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="1",
- properties={"$browser": "Firefox"},
- )
- with time_machine.travel("2012-01-15T04:01:38.200Z", tick=False):
- _create_event(
- team=self.team,
- event="user did things",
- distinct_id="1",
- properties={"$browser": "Chrome"},
- )
- with time_machine.travel("2012-01-16T04:01:38.200Z", tick=False):
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "insight": "FUNNELS",
- "entity_type": "events",
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "math": "total",
- },
- {
- "id": "user did things",
- "type": "events",
- "order": 1,
- "math": "total",
- },
- ],
- "properties": json.dumps(
- [
- {
- "key": "toInt(person.properties.int_value) < 10 and 'bla' != 'a%sd'",
- "type": "hogql",
- },
- ]
- ),
- "funnel_aggregate_by_hogql": "properties.$browser",
- "funnel_viz_type": "time_to_convert",
- "date_from": "-14d",
- "date_to": None,
- },
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- response_json = response.json()
- self.assertEqual(response_json["result"]["bins"], [[4.0, 1], [64.0, 0]])
- self.assertEqual(response_json["result"]["average_conversion_time"], 4.0)
- self.assertEqual(response_json["timezone"], "UTC")
-
- def test_insight_funnels_hogql_aggregating_trends(self) -> None:
- with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
- _create_person(team=self.team, distinct_ids=["1"], properties={"int_value": 1})
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="1",
- properties={"$browser": "Chrome"},
- )
- with time_machine.travel("2012-01-15T04:01:36.500Z", tick=False):
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="1",
- properties={"$browser": "Firefox"},
- )
- with time_machine.travel("2012-01-15T04:01:38.200Z", tick=False):
- _create_event(
- team=self.team,
- event="user did things",
- distinct_id="1",
- properties={"$browser": "Chrome"},
- )
- with time_machine.travel("2012-01-16T04:01:38.200Z", tick=False):
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "insight": "FUNNELS",
- "entity_type": "events",
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "user did things", "type": "events", "order": 1},
- ],
- "properties": json.dumps(
- [
- {
- "key": "toInt(person.properties.int_value) < 10 and 'bla' != 'a%sd'",
- "type": "hogql",
- },
- ]
- ),
- "funnel_aggregate_by_hogql": "properties.$browser",
- "funnel_viz_type": "trends",
- },
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- response_json = response.json()
- self.assertEqual(len(response_json["result"]), 1)
- self.assertEqual(
- response_json["result"][0]["data"],
- [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, 0.0],
- )
- self.assertEqual(
- response_json["result"][0]["days"],
- [
- "2012-01-09",
- "2012-01-10",
- "2012-01-11",
- "2012-01-12",
- "2012-01-13",
- "2012-01-14",
- "2012-01-15",
- "2012-01-16",
- ],
- )
- self.assertEqual(
- response_json["result"][0]["labels"],
- [
- "9-Jan-2012",
- "10-Jan-2012",
- "11-Jan-2012",
- "12-Jan-2012",
- "13-Jan-2012",
- "14-Jan-2012",
- "15-Jan-2012",
- "16-Jan-2012",
- ],
- )
- self.assertEqual(response_json["timezone"], "UTC")
-
def test_insight_returns_cached_hogql(self) -> None:
insight = Insight.objects.create(
query={
@@ -4969,70 +4161,6 @@ class TestInsightErrorHandling(ClickhouseTestMixin, APIBaseTest):
self.assertIn(error_message, query_status["error_message"])
self.assertEqual(query_status["error_code"], expected_error_code)
- @parameterized.expand(
- [
- ("ExposedCHQueryError", "ClickHouse trend error"),
- ("ExposedHogQLError", "HogQL trend error"),
- ("HogVMException", "Global variable not found: variables"),
- ]
- )
- @patch("products.product_analytics.backend.presentation.insight.process_query_dict")
- def test_trend_returns_400_for_exposed_errors(
- self, error_type: str, error_message: str, mock_process: mock.MagicMock
- ) -> None:
- from posthog.hogql.errors import ExposedHogQLError
-
- from posthog.errors import ExposedCHQueryError
-
- from common.hogvm.python.utils import HogVMException
-
- error_classes: dict[str, type] = {
- "ExposedCHQueryError": ExposedCHQueryError,
- "ExposedHogQLError": ExposedHogQLError,
- "HogVMException": HogVMException,
- }
- mock_process.side_effect = error_classes[error_type](error_message)
-
- response = self.client.get(
- f"/api/environments/{self.team.id}/insights/trend/",
- data={"events": json.dumps([{"id": "$pageview"}])},
- )
-
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn(error_message, str(response.json()))
-
- @parameterized.expand(
- [
- ("ExposedCHQueryError", "ClickHouse funnel error"),
- ("ExposedHogQLError", "HogQL funnel error"),
- ("HogVMException", "Global variable not found: variables"),
- ]
- )
- @patch("products.product_analytics.backend.presentation.insight.process_query_dict")
- def test_funnel_returns_400_for_exposed_errors(
- self, error_type: str, error_message: str, mock_process: mock.MagicMock
- ) -> None:
- from posthog.hogql.errors import ExposedHogQLError
-
- from posthog.errors import ExposedCHQueryError
-
- from common.hogvm.python.utils import HogVMException
-
- error_classes: dict[str, type] = {
- "ExposedCHQueryError": ExposedCHQueryError,
- "ExposedHogQLError": ExposedHogQLError,
- "HogVMException": HogVMException,
- }
- mock_process.side_effect = error_classes[error_type](error_message)
-
- response = self.client.get(
- f"/api/environments/{self.team.id}/insights/funnel/",
- data={"events": json.dumps([{"id": "$pageview"}, {"id": "$pageleave"}])},
- )
-
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn(error_message, str(response.json()))
-
class TestInsightBulkDelete(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
def _create_insight(self, name: str = "My insight") -> Insight:
diff --git a/products/product_analytics/backend/tests/api/test_insight_funnels.py b/products/product_analytics/backend/tests/api/test_insight_funnels.py
deleted file mode 100644
index 041c24e98eb5..000000000000
--- a/products/product_analytics/backend/tests/api/test_insight_funnels.py
+++ /dev/null
@@ -1,597 +0,0 @@
-from datetime import datetime
-from typing import Any, Union
-
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
-
-from posthog.test.test_journeys import journeys_for
-
-
-class ClickhouseTestFunnelTypes(ClickhouseTestMixin, APIBaseTest):
- def test_funnel_unordered_basic_post(self):
- journeys_for(
- {
- "1": [{"event": "step one"}, {"event": "step two"}],
- "2": [{"event": "step one"}, {"event": "step two"}],
- },
- self.team,
- )
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "events": [
- {"id": "step one", "type": "events", "order": 0},
- {"id": "step two", "type": "events", "order": 1},
- ],
- "funnel_window_days": 14,
- "funnel_order_type": "unordered",
- "insight": "funnels",
- },
- ).json()
-
- self.assertEqual(len(response["result"]), 2)
- self.assertEqual(response["result"][0]["name"], "Completed 1 step")
- self.assertEqual(response["result"][1]["name"], "Completed 2 steps")
- self.assertEqual(response["result"][0]["count"], 2)
- self.assertEqual(response["result"][1]["count"], 2)
-
- def test_funnel_strict_basic_post(self):
- journeys_for(
- {
- "1": [{"event": "step one"}, {"event": "step two"}],
- "2": [{"event": "step one"}, {"event": "blahh"}, {"event": "step two"}],
- },
- self.team,
- )
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "events": [
- {"id": "step one", "type": "events", "order": 0},
- {"id": "step two", "type": "events", "order": 1},
- ],
- "funnel_window_days": 14,
- "funnel_order_type": "strict",
- "insight": "funnels",
- },
- ).json()
-
- self.assertEqual(len(response["result"]), 2)
- self.assertEqual(response["result"][0]["name"], "step one")
- self.assertEqual(response["result"][1]["name"], "step two")
- self.assertEqual(response["result"][0]["count"], 2)
- self.assertEqual(response["result"][1]["count"], 1)
-
- def test_funnel_trends_basic_post(self):
- journeys_for(
- {
- "user_one": [
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- "user_two": [
- {"event": "step one", "timestamp": datetime(2021, 5, 2)},
- {"event": "step two", "timestamp": datetime(2021, 5, 4)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- },
- self.team,
- )
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "events": [
- {"id": "step one", "type": "events", "order": 0},
- {"id": "step two", "type": "events", "order": 1},
- {"id": "step three", "type": "events", "order": 2},
- ],
- "funnel_window_days": 7,
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 23:59:59",
- "funnel_viz_type": "trends",
- },
- ).json()
-
- self.assertEqual(len(response["result"]), 1)
- self.assertEqual(response["result"][0]["count"], 7)
- self.assertEqual(response["result"][0]["data"], [100, 100, 0, 0, 0, 0, 0])
-
- def test_funnel_trends_unordered_basic_post(self):
- journeys_for(
- {
- "user_one": [
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step three", "timestamp": datetime(2021, 5, 3)},
- {"event": "step two", "timestamp": datetime(2021, 5, 5)},
- ],
- "user_two": [
- {"event": "step three", "timestamp": datetime(2021, 5, 2)},
- {"event": "step one", "timestamp": datetime(2021, 5, 4)},
- {"event": "step two", "timestamp": datetime(2021, 5, 5)},
- ],
- },
- self.team,
- )
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "events": [
- {"id": "step one", "type": "events", "order": 0},
- {"id": "step two", "type": "events", "order": 1},
- {"id": "step three", "type": "events", "order": 2},
- ],
- "funnel_window_days": 7,
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 23:59:59",
- "funnel_viz_type": "trends",
- "funnel_order_type": "unordered",
- },
- ).json()
-
- self.assertEqual(len(response["result"]), 1)
- self.assertEqual(response["result"][0]["count"], 7)
- self.assertEqual(response["result"][0]["data"], [100, 100, 0, 0, 0, 0, 0])
-
- def test_funnel_trends_basic_post_backwards_compatibility(self):
- journeys_for(
- {
- "user_one": [
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- "user_two": [
- {"event": "step one", "timestamp": datetime(2021, 5, 2)},
- {"event": "step two", "timestamp": datetime(2021, 5, 4)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- },
- self.team,
- )
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "events": [
- {"id": "step one", "type": "events", "order": 0},
- {"id": "step two", "type": "events", "order": 1},
- {"id": "step three", "type": "events", "order": 2},
- ],
- "funnel_window_days": 7,
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 23:59:59",
- "display": "ActionsLineGraph",
- },
- ).json()
-
- self.assertEqual(len(response["result"]), 1)
- self.assertEqual(response["result"][0]["count"], 7)
- self.assertEqual(response["result"][0]["data"], [100, 100, 0, 0, 0, 0, 0])
-
- def test_funnel_trends_strict_basic_post(self):
- journeys_for(
- {
- "user_one": [
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- "user_two": [
- {"event": "step one", "timestamp": datetime(2021, 5, 2)},
- {"event": "step two", "timestamp": datetime(2021, 5, 4)},
- {"event": "blah", "timestamp": datetime(2021, 5, 4, 2)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- "user_three": [
- {"event": "step one", "timestamp": datetime(2021, 5, 2)},
- {"event": "step two", "timestamp": datetime(2021, 5, 4)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- },
- self.team,
- )
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "events": [
- {"id": "step one", "type": "events", "order": 0},
- {"id": "step two", "type": "events", "order": 1},
- {"id": "step three", "type": "events", "order": 2},
- ],
- "funnel_window_days": 7,
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 23:59:59",
- "funnel_viz_type": "trends",
- "funnel_order_type": "strict",
- },
- ).json()
-
- self.assertEqual(len(response["result"]), 1)
- self.assertEqual(response["result"][0]["count"], 7)
- self.assertEqual(response["result"][0]["data"], [100, 50, 0, 0, 0, 0, 0])
-
- @snapshot_clickhouse_queries
- def test_funnel_time_to_convert_auto_bins(self):
- journeys_for(
- {
- "user a": [
- {"event": "step one", "timestamp": datetime(2021, 6, 8, 18)},
- {"event": "blah", "timestamp": datetime(2021, 6, 8, 18, 30)},
- {"event": "step two", "timestamp": datetime(2021, 6, 8, 19)},
- # Converted from 0 to 1 in 3600 s
- {"event": "step three", "timestamp": datetime(2021, 6, 8, 21)},
- ],
- "user b": [
- {"event": "step one", "timestamp": datetime(2021, 6, 9, 13)},
- {"event": "step two", "timestamp": datetime(2021, 6, 9, 13, 37)},
- # Converted from 0 to 1 in 2200 s
- ],
- "user c": [
- {"event": "step one", "timestamp": datetime(2021, 6, 11, 7)},
- {"event": "step two", "timestamp": datetime(2021, 6, 12, 6)},
- # Converted from 0 to 1 in 82_800 s
- ],
- },
- self.team,
- )
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "insight": "funnels",
- "funnel_viz_type": "time_to_convert",
- "interval": "day",
- "date_from": "2021-06-07 00:00:00",
- "date_to": "2021-06-13 23:59:59",
- "funnel_to_step": 1,
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- },
- )
-
- self.assertEqual(response.status_code, 200)
- response_data = response.json()
- response_data.pop("last_refresh")
- self.assertEqual(
- response_data,
- response_data
- | {
- "is_cached": False,
- "timezone": "UTC",
- "result": {
- "bins": [[2220, 2], [42510, 0], [82800, 1]],
- "average_conversion_time": 29540,
- "median_conversion_time": 3600.0,
- },
- },
- )
-
- @snapshot_clickhouse_queries
- def test_funnel_time_to_convert_auto_bins_strict(self):
- journeys_for(
- {
- "user a": [
- {"event": "step one", "timestamp": datetime(2021, 6, 8, 18)},
- {"event": "step two", "timestamp": datetime(2021, 6, 8, 19)},
- # Converted from 0 to 1 in 3600 s
- {"event": "step three", "timestamp": datetime(2021, 6, 8, 21)},
- ],
- "user b": [
- {"event": "step one", "timestamp": datetime(2021, 6, 9, 13)},
- {"event": "step two", "timestamp": datetime(2021, 6, 9, 13, 37)},
- # Converted from 0 to 1 in 2200 s
- ],
- "user c": [
- {"event": "step one", "timestamp": datetime(2021, 6, 11, 7)},
- {"event": "step two", "timestamp": datetime(2021, 6, 12, 6)},
- # Converted from 0 to 1 in 82_800 s
- ],
- },
- self.team,
- )
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "insight": "funnels",
- "funnel_viz_type": "time_to_convert",
- "funnel_order_type": "strict",
- "interval": "day",
- "date_from": "2021-06-07 00:00:00",
- "date_to": "2021-06-13 23:59:59",
- "funnel_to_step": 1,
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- },
- )
-
- self.assertEqual(response.status_code, 200)
- response_data = response.json()
- response_data.pop("last_refresh")
- self.assertEqual(
- response_data,
- response_data
- | {
- "is_cached": False,
- "timezone": "UTC",
- "result": {
- "bins": [[2220.0, 2], [42510.0, 0], [82800.0, 1]],
- "average_conversion_time": 29540.0,
- "median_conversion_time": 3600.0,
- },
- },
- )
-
- @snapshot_clickhouse_queries
- def test_funnel_time_to_convert_auto_bins_unordered(self):
- journeys_for(
- {
- "user a": [
- {"event": "step one", "timestamp": datetime(2021, 6, 8, 18)},
- {"event": "step two", "timestamp": datetime(2021, 6, 8, 19)},
- # Converted from 0 to 1 in 3600 s
- {"event": "step three", "timestamp": datetime(2021, 6, 8, 21)},
- ],
- "user b": [
- {"event": "step two", "timestamp": datetime(2021, 6, 9, 13)},
- {"event": "step one", "timestamp": datetime(2021, 6, 9, 13, 37)},
- # Converted from 0 to 1 in 2200 s
- ],
- "user c": [
- {"event": "step one", "timestamp": datetime(2021, 6, 11, 7)},
- {"event": "step two", "timestamp": datetime(2021, 6, 12, 6)},
- # Converted from 0 to 1 in 82_800 s
- ],
- },
- self.team,
- )
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "insight": "funnels",
- "funnel_viz_type": "time_to_convert",
- "funnel_order_type": "unordered",
- "interval": "day",
- "date_from": "2021-06-07 00:00:00",
- "date_to": "2021-06-13 23:59:59",
- "funnel_to_step": 1,
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- },
- )
-
- self.assertEqual(response.status_code, 200)
- response_data = response.json()
- response_data.pop("last_refresh")
- self.assertEqual(
- response_data,
- response_data
- | {
- "is_cached": False,
- "timezone": "UTC",
- "result": {
- "bins": [[2220.0, 2], [42510.0, 0], [82800.0, 1]],
- "average_conversion_time": 29540.0,
- "median_conversion_time": 3600.0,
- },
- },
- )
-
- def test_funnel_invalid_action_handled(self):
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {"actions": [{"id": 666, "type": "actions", "order": 0}, {"id": 666, "type": "actions", "order": 0}]},
- )
-
- self.assertEqual(response.status_code, 400)
- self.assertEqual(
- response.json(),
- self.validation_error_response("Action ID 666 does not exist!"),
- )
-
- def test_funnel_basic_exclusions(self):
- journeys_for(
- {
- "1": [
- {"event": "step one"},
- {"event": "step x"},
- {"event": "step two"},
- ],
- "2": [{"event": "step one"}, {"event": "step two"}],
- },
- self.team,
- )
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "events": [
- {"id": "step one", "type": "events", "order": 0},
- {"id": "step two", "type": "events", "order": 1},
- ],
- "exclusions": [
- {
- "id": "step x",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- }
- ],
- "funnel_window_days": 14,
- "insight": "funnels",
- },
- ).json()
-
- self.assertEqual(len(response["result"]), 2)
- self.assertEqual(response["result"][0]["name"], "step one")
- self.assertEqual(response["result"][1]["name"], "step two")
- self.assertEqual(response["result"][0]["count"], 1)
- self.assertEqual(response["result"][1]["count"], 1)
-
- def test_funnel_invalid_exclusions(self):
- journeys_for(
- {
- "1": [
- {"event": "step one"},
- {"event": "step x"},
- {"event": "step two"},
- ],
- "2": [{"event": "step one"}, {"event": "step two"}],
- },
- self.team,
- )
-
- for exclusion_id, exclusion_from_step, exclusion_to_step, error in [
- ("step one", 0, 1, True),
- ("step two", 0, 1, True),
- ("step two", 0, 2, True),
- ("step one", 0, 2, True),
- ("step three", 0, 2, True),
- ("step three", 0, 1, False),
- ]:
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel/",
- {
- "events": [
- {"id": "step one", "type": "events", "order": 0},
- {"id": "step two", "type": "events", "order": 1},
- {"id": "step three", "type": "events", "order": 2},
- ],
- "exclusions": [
- {
- "id": exclusion_id,
- "type": "events",
- "funnel_from_step": exclusion_from_step,
- "funnel_to_step": exclusion_to_step,
- }
- ],
- "funnel_window_days": 14,
- "insight": "funnels",
- },
- )
-
- if error:
- self.assertEqual(response.status_code, 400)
- self.assertEqual(
- response.json(),
- self.validation_error_response(
- "Exclusion steps cannot contain an event that's part of funnel steps.",
- code="funnel_exclusions_invalid",
- ),
- )
- else:
- self.assertEqual(response.status_code, 200)
-
- def test_single_property_breakdown(self):
- journeys_for(
- {
- "person1": [
- {
- "event": "$pageview",
- "properties": {"$browser": "Chrome", "$browser_version": 95},
- },
- {
- "event": "$pageleave",
- "properties": {"$browser": "Chrome", "$browser_version": 95},
- },
- ],
- "person2": [
- {
- "event": "$pageview",
- "properties": {"$browser": "Safari", "$browser_version": 11},
- },
- {
- "event": "$pageview",
- "properties": {"$browser": "Safari", "$browser_version": 11},
- },
- ],
- },
- self.team,
- )
-
- filter_with_breakdown = {
- "insight": "FUNNELS",
- "date_from": "-14d",
- "actions": [],
- "events": [
- {"id": "$pageview", "name": "$pageview", "type": "events", "order": 0},
- {
- "id": "$pageleave",
- "name": "$pageleave",
- "type": "events",
- "order": 1,
- },
- ],
- "display": "FunnelViz",
- "interval": "day",
- "properties": [],
- "funnel_viz_type": "steps",
- "exclusions": [],
- "breakdown": "$browser",
- "breakdown_type": "event",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- }
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/insights/funnel?refresh=true",
- filter_with_breakdown,
- )
- self.assertEqual(200, response.status_code)
-
- response_data = response.json()
- result = response_data["result"]
-
- self.assertEqual(result[0][0]["name"], "$pageview")
- self.assertEqual(result[0][0]["count"], 1)
- self.assertEqual("Chrome", result[0][0]["breakdown"])
- self.assertEqual("Chrome", result[0][0]["breakdown_value"])
-
- self.assertEqual(result[0][1]["name"], "$pageleave")
- self.assertEqual(result[0][1]["count"], 1)
- self.assertEqual("Chrome", result[0][1]["breakdown"])
- self.assertEqual("Chrome", result[0][1]["breakdown_value"])
-
- self.assertEqual(result[1][0]["name"], "$pageview")
- self.assertEqual(result[1][0]["count"], 1)
- self.assertEqual("Safari", result[1][0]["breakdown"])
- self.assertEqual("Safari", result[1][0]["breakdown_value"])
-
- self.assertEqual(result[1][1]["name"], "$pageleave")
- self.assertEqual(result[1][1]["count"], 0)
- self.assertEqual("Safari", result[1][1]["breakdown"])
- self.assertEqual("Safari", result[1][1]["breakdown_value"])
-
- @staticmethod
- def as_result(breakdown_properties: Union[str, list[str]]) -> dict[str, Any]:
- return {
- "action_id": "$pageview",
- "name": "$pageview",
- "custom_name": None,
- "order": 0,
- "people": ["a uuid"],
- "count": 1,
- "type": "events",
- "average_conversion_time": None,
- "median_conversion_time": None,
- "breakdown": breakdown_properties,
- "breakdown_value": breakdown_properties,
- }