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.

fix(groups): read group key columns in the related actors query (#107324)

posthog[bot]275fefb26357
diff --git a/ee/clickhouse/queries/related_actors_query.py b/ee/clickhouse/queries/related_actors_query.py
index df9960035a2d..b22bde21adb9 100644
--- a/ee/clickhouse/queries/related_actors_query.py
+++ b/ee/clickhouse/queries/related_actors_query.py
@@ -1,6 +1,6 @@
from datetime import timedelta
from functools import cached_property
-from typing import Optional, Union, cast
+from typing import Any, Optional, Union, cast
from django.utils.timezone import now
@@ -54,13 +54,7 @@ class RelatedActorsQuery:
results: list[SerializedActor] = []
results.extend(self._query_related_people())
- from posthog.models.group_type_mapping import get_group_types_for_project
-
- group_type_indexes = [
- m["group_type_index"]
- for m in get_group_types_for_project(self.team.project_id)
- if m["group_type_index"] != self.group_type_index
- ]
+ group_type_indexes = [index for index in self._group_types if index != self.group_type_index]
results.extend(self._query_related_groups(group_type_indexes=group_type_indexes))
return results
@@ -73,16 +67,23 @@ class RelatedActorsQuery:
with personhog_caller_tag("persons/related-actors"):
return get_serialized_people(self.team, person_ids)
+ @cached_property
+ def _group_types(self) -> dict[int, dict[str, Any]]:
+ from posthog.models.group_type_mapping import get_group_types_for_project
+
+ return {m["group_type_index"]: m for m in get_group_types_for_project(self.team.project_id)}
+
def _group_key_field(self, group_index: int) -> ast.Expr:
- # Read the group key from the raw event JSON rather than the `$group_N` field: the latter is
- # zeroed for events older than the GroupTypeMapping.created_at, but the legacy raw query
- # matched all events regardless, so we go to the JSON to preserve that behavior.
- # JSONExtractString returns a non-nullable String (empty when missing), matching the
- # materialized column's type so tuple/IN comparisons stay non-nullable.
- return ast.Call(
- name="JSONExtractString",
- args=[ast.Field(chain=["events", "properties"]), ast.Constant(value=f"$group_{group_index}")],
- )
+ # Read the group key column, not the JSON in `properties`. On the native-JSON events table a
+ # JSON read rebuilds the whole property sub-object per row, and for heavy actors that goes
+ # over the ClickHouse memory limit.
+ # When the GroupTypeMapping has a created_at, HogQL zeroes `$group_N` for older events and
+ # keeps the raw column as `_$group_N_raw`. The legacy raw query matched all events, so we
+ # read the raw column to keep that behavior.
+ mapping = self._group_types.get(group_index)
+ if mapping and mapping["created_at"]:
+ return ast.Field(chain=["events", f"_$group_{group_index}_raw"])
+ return ast.Field(chain=["events", f"$group_{group_index}"])
def _query_related_people_ids(self) -> list:
# Resolve distinct_ids seen on events for this group, then map them to persons via
diff --git a/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr b/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr
index 5dc520101d57..984559d22cad 100644
--- a/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr
+++ b/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr
@@ -11,7 +11,7 @@
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 events__override ON equals(events.distinct_id, events__override.distinct_id) ARRAY
- JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, nullIf(events.`$group_0`, '')), tuple(1, nullIf(events.`$group_1`, ''))]) AS tuples
+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, events.`$group_0`), tuple(1, events.`$group_1`)]) AS tuples
WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'))
LIMIT 100 SETTINGS readonly=2,
max_execution_time=60,
@@ -60,7 +60,7 @@
SELECT DISTINCT tuples.1 AS group_type_index,
tuples.2 AS group_key
FROM events ARRAY
- JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(1, nullIf(events.`$group_1`, ''))]) AS tuples
+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(1, events.`$group_1`)]) AS tuples
WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2024-12-01 12:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.`$group_0`, 'org:1'))
LIMIT 100 SETTINGS readonly=2,
max_execution_time=60,
diff --git a/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.new_events_schema.ambr b/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.new_events_schema.ambr
index 7c4361b8117c..0ba374f2b768 100644
--- a/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.new_events_schema.ambr
+++ b/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.new_events_schema.ambr
@@ -11,7 +11,7 @@
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 events__override ON equals(events.distinct_id, events__override.distinct_id) ARRAY
- JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, JSONExtractString(ifNull(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_0`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_0`)), if(isNull(nullIf(toString(events.properties.`$group_0`), '')), NULL, nullIf(nullIf(toJSONString(events.properties.`$group_0`), '[]'), '{}'))), ''))), tuple(1, JSONExtractString(ifNull(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_1`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_1`)), if(isNull(nullIf(toString(events.properties.`$group_1`), '')), NULL, nullIf(nullIf(toJSONString(events.properties.`$group_1`), '[]'), '{}'))), '')))]) AS tuples
+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, events.properties.`$group_0`), tuple(1, events.properties.`$group_1`)]) AS tuples
WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'))
LIMIT 100 SETTINGS readonly=2,
max_execution_time=60,
@@ -33,8 +33,8 @@
SELECT DISTINCT tuples.1 AS group_type_index,
tuples.2 AS group_key
FROM events_json AS events ARRAY
- JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(1, JSONExtractString(ifNull(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_1`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_1`)), if(isNull(nullIf(toString(events.properties.`$group_1`), '')), NULL, nullIf(nullIf(toJSONString(events.properties.`$group_1`), '[]'), '{}'))), '')))]) AS tuples
- WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2024-12-01 12:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(JSONExtractString(ifNull(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_0`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_0`)), if(isNull(nullIf(toString(events.properties.`$group_0`), '')), NULL, nullIf(nullIf(toJSONString(events.properties.`$group_0`), '[]'), '{}'))), '')), 'org:1'))
+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(1, events.properties.`$group_1`)]) AS tuples
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2024-12-01 12:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.properties.`$group_0`, 'org:1'))
LIMIT 100 SETTINGS readonly=2,
max_execution_time=60,
allow_experimental_object_type=1,
@@ -63,7 +63,7 @@
WHERE globalIn(person_distinct_ids.distinct_id,
(SELECT events.distinct_id AS distinct_id
FROM events_json AS events
- WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2024-12-01 12:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(JSONExtractString(ifNull(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_0`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_0`)), if(isNull(nullIf(toString(events.properties.`$group_0`), '')), NULL, nullIf(nullIf(toJSONString(events.properties.`$group_0`), '[]'), '{}'))), '')), 'org:1'))))
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2024-12-01 12:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.properties.`$group_0`, 'org:1'))))
LIMIT 100 SETTINGS readonly=2,
max_execution_time=60,
allow_experimental_object_type=1,
diff --git a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr
index 36f17efb932d..2bdf7cb85221 100644
--- a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr
+++ b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr
@@ -34,7 +34,7 @@
SELECT DISTINCT tuples.1 AS group_type_index,
tuples.2 AS group_key
FROM events ARRAY
- JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(1, nullIf(events.`$group_1`, ''))]) AS tuples
+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(1, events.`$group_1`)]) AS tuples
WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2021-02-09 00:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.`$group_0`, '0::0'))
LIMIT 100 SETTINGS readonly=2,
max_execution_time=60,
@@ -63,7 +63,7 @@
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 events__override ON equals(events.distinct_id, events__override.distinct_id) ARRAY
- JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, nullIf(events.`$group_0`, '')), tuple(1, nullIf(events.`$group_1`, ''))]) AS tuples
+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, events.`$group_0`), tuple(1, events.`$group_1`)]) AS tuples
WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'))
LIMIT 100 SETTINGS readonly=2,
max_execution_time=60,
diff --git a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.new_events_schema.ambr b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.new_events_schema.ambr
index 83af0c7ffc81..2db95c73845d 100644
--- a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.new_events_schema.ambr
+++ b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.new_events_schema.ambr
@@ -5,8 +5,8 @@
SELECT DISTINCT tuples.1 AS group_type_index,
tuples.2 AS group_key
FROM events_json AS events ARRAY
- JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(1, JSONExtractString(ifNull(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_1`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_1`)), if(isNull(nullIf(toString(events.properties.`$group_1`), '')), NULL, nullIf(nullIf(toJSONString(events.properties.`$group_1`), '[]'), '{}'))), '')))]) AS tuples
- WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2021-02-09 00:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(JSONExtractString(ifNull(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_0`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_0`)), if(isNull(nullIf(toString(events.properties.`$group_0`), '')), NULL, nullIf(nullIf(toJSONString(events.properties.`$group_0`), '[]'), '{}'))), '')), '0::0'))
+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(1, events.properties.`$group_1`)]) AS tuples
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2021-02-09 00:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.properties.`$group_0`, '0::0'))
LIMIT 100 SETTINGS readonly=2,
max_execution_time=60,
allow_experimental_object_type=1,
@@ -36,7 +36,7 @@
WHERE globalIn(person_distinct_ids.distinct_id,
(SELECT events.distinct_id AS distinct_id
FROM events_json AS events
- WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2021-02-09 00:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(JSONExtractString(ifNull(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_0`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_0`)), if(isNull(nullIf(toString(events.properties.`$group_0`), '')), NULL, nullIf(nullIf(toJSONString(events.properties.`$group_0`), '[]'), '{}'))), '')), '0::0'))))
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2021-02-09 00:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.properties.`$group_0`, '0::0'))))
LIMIT 100 SETTINGS readonly=2,
max_execution_time=60,
allow_experimental_object_type=1,
@@ -65,7 +65,7 @@
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 events__override ON equals(events.distinct_id, events__override.distinct_id) ARRAY
- JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, JSONExtractString(ifNull(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_0`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_0`)), if(isNull(nullIf(toString(events.properties.`$group_0`), '')), NULL, nullIf(nullIf(toJSONString(events.properties.`$group_0`), '[]'), '{}'))), ''))), tuple(1, JSONExtractString(ifNull(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_1`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$group_1`)), if(isNull(nullIf(toString(events.properties.`$group_1`), '')), NULL, nullIf(nullIf(toJSONString(events.properties.`$group_1`), '[]'), '{}'))), '')))]) AS tuples
+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, events.properties.`$group_0`), tuple(1, events.properties.`$group_1`)]) AS tuples
WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'))
LIMIT 100 SETTINGS readonly=2,
max_execution_time=60,
diff --git a/products/groups/frontend/logics/relatedGroupsLogic.test.ts b/products/groups/frontend/logics/relatedGroupsLogic.test.ts
new file mode 100644
index 000000000000..61a1a34f0fd2
--- /dev/null
+++ b/products/groups/frontend/logics/relatedGroupsLogic.test.ts
@@ -0,0 +1,43 @@
+import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import { initKeaTests } from '~/test/init'
+
+import { relatedGroupsLogic } from './relatedGroupsLogic'
+
+jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
+ lemonToast: { info: jest.fn(), error: jest.fn(), warning: jest.fn(), success: jest.fn() },
+}))
+
+describe('relatedGroupsLogic', () => {
+ beforeEach(() => {
+ initKeaTests()
+ jest.mocked(lemonToast.error).mockClear()
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('does not show an error toast when the request fails after unmount', async () => {
+ let failRequest: () => void = () => {}
+ let requestSignal: AbortSignal | undefined
+ jest.spyOn(api, 'get').mockImplementation(
+ (_url, options) =>
+ new Promise((_resolve, reject) => {
+ requestSignal = options?.signal
+ options?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))
+ failRequest = () => reject({ status: 500, detail: 'Query exceeded the memory limit' })
+ })
+ )
+
+ const logic = relatedGroupsLogic({ groupTypeIndex: null, id: 'person-uuid' })
+ logic.mount()
+ logic.unmount()
+ failRequest()
+ await new Promise((resolve) => setTimeout(resolve, 0))
+
+ expect(requestSignal?.aborted).toBe(true)
+ expect(lemonToast.error).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/groups/frontend/logics/relatedGroupsLogic.ts b/products/groups/frontend/logics/relatedGroupsLogic.ts
index 365e08b34954..d4b3dc541154 100644
--- a/products/groups/frontend/logics/relatedGroupsLogic.ts
+++ b/products/groups/frontend/logics/relatedGroupsLogic.ts
@@ -82,11 +82,16 @@ export const relatedGroupsLogic = kea<relatedGroupsLogicType>([
key((props) => `${props.groupTypeIndex ?? 'person'}-${props.id}`),
path(['scenes', 'groups', 'relatedGroupsLogic']),
connect(() => ({ values: [teamLogic, ['currentTeamId']] })),
- loaders(({ values, props }) => ({
+ loaders(({ values, props, cache }) => ({
relatedActors: [
[] as ActorType[],
{
loadRelatedActors: async () => {
+ // Abort on unmount so a slow request that fails later does not toast on the next page.
+ const controller = new AbortController()
+ cache.disposables.add(() => () => controller.abort(), 'relatedActorsRequest', {
+ pauseOnPageHidden: false,
+ })
const url = `api/projects/${values.currentTeamId}/groups/related?${toParams({
group_type_index: props.groupTypeIndex,
id: props.id,
@@ -94,7 +99,7 @@ export const relatedGroupsLogic = kea<relatedGroupsLogicType>([
// groupsRelatedList returns RelatedActorApi, which ActorType cannot hold:
// ~/types has is_identified non-nullable and distinct_ids optional.
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
- return await api.get(url)
+ return await api.get(url, { signal: controller.signal })
},
setGroup: () => [],
},