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(ingestion): drop $groupidentify with a group type over 400 chars (#119282)

Eli Reisman32aa40c3690c
diff --git a/nodejs/src/common/groups/group-type-manager.test.ts b/nodejs/src/common/groups/group-type-manager.test.ts
index 867628b2084b..d4c2727aaace 100644
--- a/nodejs/src/common/groups/group-type-manager.test.ts
+++ b/nodejs/src/common/groups/group-type-manager.test.ts
@@ -156,6 +156,15 @@ describe('GroupTypeManager()', () => {
})
describe('fetchGroupTypeIndex()', () => {
+ it('returns null without inserting when the type exceeds the column length', async () => {
+ jest.mocked(hub.groupRepository.insertGroupType).mockClear()
+
+ const groupType = 'a'.repeat(401)
+ expect(await groupTypeManager.fetchGroupTypeIndex(teamId, projectId, groupType, TEST_TIMESTAMP)).toBeNull()
+
+ expect(hub.groupRepository.insertGroupType).not.toHaveBeenCalled()
+ })
+
it('fetches an already existing value', async () => {
await hub.groupRepository.insertGroupType(teamId, projectId, 'foo', 0, TEST_TIMESTAMP)
await hub.groupRepository.insertGroupType(teamId, projectId, 'bar', 1, TEST_TIMESTAMP)
diff --git a/nodejs/src/common/groups/group-type-manager.ts b/nodejs/src/common/groups/group-type-manager.ts
index 551f47025718..f935c6ea250d 100644
--- a/nodejs/src/common/groups/group-type-manager.ts
+++ b/nodejs/src/common/groups/group-type-manager.ts
@@ -1,7 +1,8 @@
import { DateTime } from 'luxon'
+import { Counter } from 'prom-client'
import { GroupRepository } from '~/common/groups/repositories/group-repository.interface'
-import { timeoutGuard } from '~/common/utils/db/utils'
+import { asPostgresParameterText, timeoutGuard } from '~/common/utils/db/utils'
import { LazyLoader, LoaderRetryOptions } from '~/common/utils/lazy-loader'
import { captureTeamEvent } from '~/common/utils/posthog'
import { TeamManager } from '~/common/utils/team-manager'
@@ -10,6 +11,14 @@ import { GroupTypeIndex, GroupTypeToColumnIndex, GroupTypesByProjectId, ProjectI
/** How many unique group types to allow per team */
export const MAX_GROUP_TYPES_PER_TEAM = 5
+/** posthog_grouptypemapping.group_type is varchar(400); a longer value makes the insert fail. */
+export const MAX_GROUP_TYPE_LENGTH = 400
+
+const groupTypeTooLongCounter = new Counter({
+ name: 'group_type_too_long_total',
+ help: 'Group type resolutions skipped because the type exceeds the column length.',
+})
+
export interface GroupTypeManagerOptions {
/** Retry transient group-type-load failures (e.g. a Postgres pooler blip) instead of letting them propagate. */
loaderRetry?: LoaderRetryOptions
@@ -80,6 +89,11 @@ export class GroupTypeManager {
groupType: string,
eventTimestamp: DateTime
): Promise<GroupTypeIndex | null> {
+ if (asPostgresParameterText(groupType).length > MAX_GROUP_TYPE_LENGTH) {
+ groupTypeTooLongCounter.inc()
+ return null
+ }
+
const existingIndex = await this.lookupGroupTypeIndex(projectId, groupType)
if (existingIndex !== null) {
return existingIndex
diff --git a/nodejs/src/common/utils/db/utils.ts b/nodejs/src/common/utils/db/utils.ts
index 2baaee696c42..6d9fdde089f8 100644
--- a/nodejs/src/common/utils/db/utils.ts
+++ b/nodejs/src/common/utils/db/utils.ts
@@ -202,6 +202,13 @@ export function sanitizeString(value: string) {
return value.replace(/\u0000/g, '\uFFFD')
}
+// The pg driver sends an object parameter as JSON text and everything else via
+// String(), so this is the text Postgres receives. String() alone throws on an
+// object whose toString is not callable, which a sender controls.
+export function asPostgresParameterText(value: unknown): string {
+ return typeof value === 'object' ? JSON.stringify(value) : String(value)
+}
+
export const surrogatesSubstitutedCounter = new Counter({
name: 'surrogates_substituted_total',
help: 'Stray UTF16 surrogates detected and removed from user input.',
diff --git a/nodejs/src/ingestion/common/ingestion-warning-types.ts b/nodejs/src/ingestion/common/ingestion-warning-types.ts
index 79ac3609ab57..86140179b644 100644
--- a/nodejs/src/ingestion/common/ingestion-warning-types.ts
+++ b/nodejs/src/ingestion/common/ingestion-warning-types.ts
@@ -38,6 +38,7 @@ export const INGESTION_WARNING_TYPES = {
person_upsert_message_size_too_large: { category: 'size', severity: 'error' },
group_upsert_message_size_too_large: { category: 'size', severity: 'error' },
group_key_too_long: { category: 'size', severity: 'error' },
+ group_type_too_long: { category: 'size', severity: 'error' },
// Person merges — rejected $identify / $create_alias / $merge_dangerously operations
cannot_merge_already_identified: { category: 'merge', severity: 'warning' },
diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-properties.test.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-properties.test.ts
index 01231e5cf30c..61d6c23d0da3 100644
--- a/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-properties.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-properties.test.ts
@@ -1,5 +1,6 @@
import { drop, ok } from '~/ingestion/framework/results'
import { createTestPipelineEvent } from '~/tests/helpers/pipeline-event'
+import { PipelineEvent } from '~/types'
import { createValidateEventPropertiesStep } from './validate-event-properties'
@@ -107,6 +108,70 @@ describe('createValidateEventPropertiesStep', () => {
})
})
+ describe('group type validation', () => {
+ const groupIdentify = (groupType: unknown): { event: PipelineEvent } => ({
+ event: createTestPipelineEvent({
+ event: '$groupidentify',
+ distinct_id: 'user123',
+ team_id: 1,
+ properties: { $group_type: groupType, $group_key: 'org_1' },
+ }),
+ })
+
+ it.each([
+ ['a string longer than 400 characters', 'a'.repeat(401), 'a'.repeat(100), 401],
+ [
+ 'an object whose JSON is longer than 400 characters',
+ { blob: 'a'.repeat(400) },
+ `{"blob":"${'a'.repeat(91)}`,
+ 411,
+ ],
+ [
+ 'an object whose toString is not callable',
+ { toString: null, padding: 'a'.repeat(401) },
+ `{"toString":null,"padding":"${'a'.repeat(72)}`,
+ 431,
+ ],
+ ])('drops $groupidentify with %s', async (_name, groupType, groupTypePreview, groupTypeLength) => {
+ const input = groupIdentify(groupType)
+
+ const result = await step(input)
+
+ expect(result).toEqual(
+ drop(
+ 'group_type_too_long',
+ [],
+ [
+ {
+ type: 'group_type_too_long',
+ details: {
+ eventUuid: '123e4567-e89b-12d3-a456-426614174000',
+ event: '$groupidentify',
+ distinctId: 'user123',
+ groupKey: 'org_1',
+ groupType: groupTypePreview,
+ groupTypeLength,
+ maxLength: 400,
+ },
+ },
+ ]
+ )
+ )
+ })
+
+ it.each([
+ ['exactly 400 characters', 'a'.repeat(400)],
+ ['a number', 7],
+ ['missing', undefined],
+ ])('allows $groupidentify with group_type %s', async (_name, groupType) => {
+ const input = groupIdentify(groupType)
+
+ const result = await step(input)
+
+ expect(result).toEqual(ok(input))
+ })
+ })
+
describe('other event types', () => {
it('should allow non-groupidentify events', async () => {
const input = {
diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-properties.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-properties.ts
index 43a4b46ede38..7f522a070714 100644
--- a/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-properties.ts
+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-properties.ts
@@ -1,15 +1,19 @@
+import { MAX_GROUP_TYPE_LENGTH } from '~/common/groups/group-type-manager'
+import { asPostgresParameterText } from '~/common/utils/db/utils'
import { drop, ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
import { PipelineEvent } from '~/types'
+// posthog_group.group_key is varchar(400).
+const MAX_GROUP_KEY_LENGTH = 400
+
export function createValidateEventPropertiesStep<T extends { event: PipelineEvent }>(): ProcessingStep<T, T> {
return async function validateEventPropertiesStep(input) {
const { event } = input
- // Validate $groupidentify group_key length
if (event.event === '$groupidentify') {
const groupKey = event.properties?.$group_key
- if (groupKey && groupKey.toString().length > 400) {
+ if (groupKey && groupKey.toString().length > MAX_GROUP_KEY_LENGTH) {
return drop(
'group_key_too_long',
[],
@@ -22,7 +26,30 @@ export function createValidateEventPropertiesStep<T extends { event: PipelineEve
distinctId: event.distinct_id,
groupKey,
groupKeyLength: groupKey.toString().length,
- maxLength: 400,
+ maxLength: MAX_GROUP_KEY_LENGTH,
+ },
+ },
+ ]
+ )
+ }
+
+ const groupType = event.properties?.$group_type
+ const groupTypeText = groupType ? asPostgresParameterText(groupType) : ''
+ if (groupTypeText.length > MAX_GROUP_TYPE_LENGTH) {
+ return drop(
+ 'group_type_too_long',
+ [],
+ [
+ {
+ type: 'group_type_too_long',
+ details: {
+ eventUuid: event.uuid,
+ event: event.event,
+ distinctId: event.distinct_id,
+ groupKey,
+ groupType: groupTypeText.substring(0, 100),
+ groupTypeLength: groupTypeText.length,
+ maxLength: MAX_GROUP_TYPE_LENGTH,
},
},
]
diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-groups-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/process-groups-step.test.ts
index 28d98117d10e..ad225ed2e766 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/process-groups-step.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/process-groups-step.test.ts
@@ -156,9 +156,16 @@ describe('createProcessGroupsStep', () => {
{ desc: 'number', groupSet: 42, receivedType: 'number' },
{ desc: 'boolean', groupSet: true, receivedType: 'boolean' },
{ desc: 'array', groupSet: ['a', 'b'], receivedType: 'array' },
+ {
+ desc: 'array and $group_type has no callable toString',
+ groupSet: ['a'],
+ receivedType: 'array',
+ groupType: { toString: null },
+ groupTypeInWarning: '{"toString":null}',
+ },
])(
'drops the event with an invalid_group_set warning when $group_set is a $desc',
- async ({ groupSet, receivedType }) => {
+ async ({ groupSet, receivedType, groupType = 'organization', groupTypeInWarning = 'organization' }) => {
mockGroupTypeManager.fetchGroupTypeIndex.mockResolvedValue(0)
const step = createStep()
@@ -167,7 +174,7 @@ describe('createProcessGroupsStep', () => {
preparedEvent: createTestPreIngestionEvent({
event: '$groupidentify',
properties: {
- $group_type: 'organization',
+ $group_type: groupType,
$group_key: 'org::5',
$group_set: groupSet,
},
@@ -183,7 +190,7 @@ describe('createProcessGroupsStep', () => {
details: expect.objectContaining({
eventUuid: 'test-uuid',
distinctId: 'test-distinct-id',
- groupType: 'organization',
+ groupType: groupTypeInWarning,
groupKey: 'org::5',
receivedType,
}),
diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-groups-step.ts b/nodejs/src/ingestion/common/steps/event-processing/process-groups-step.ts
index 5485947f002a..dcb823f63243 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/process-groups-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/process-groups-step.ts
@@ -1,7 +1,7 @@
import { DateTime } from 'luxon'
import { GroupTypeManager } from '~/common/groups/group-type-manager'
-import { sanitizeString } from '~/common/utils/db/utils'
+import { asPostgresParameterText, sanitizeString } from '~/common/utils/db/utils'
import { logger } from '~/common/utils/logger'
import { captureException } from '~/common/utils/posthog'
import { TeamManager } from '~/common/utils/team-manager'
@@ -123,7 +123,7 @@ function validateGroupSet(preparedEvent: PreIngestionEvent): PipelineWarning | n
details: {
eventUuid: preparedEvent.eventUuid,
distinctId: preparedEvent.distinctId,
- groupType: String(groupType),
+ groupType: asPostgresParameterText(groupType),
groupKey: sanitizeString(String(groupKey)),
receivedType: Array.isArray(groupPropertiesToSet) ? 'array' : typeof groupPropertiesToSet,
},
diff --git a/rust/common/ingestion_warnings/warning_types.generated.json b/rust/common/ingestion_warnings/warning_types.generated.json
index f4492ab5cc7f..45b0fa59c3cc 100644
--- a/rust/common/ingestion_warnings/warning_types.generated.json
+++ b/rust/common/ingestion_warnings/warning_types.generated.json
@@ -115,6 +115,12 @@
"severity": "error",
"captureProduced": false
},
+ {
+ "type": "group_type_too_long",
+ "category": "size",
+ "severity": "error",
+ "captureProduced": false
+ },
{
"type": "group_upsert_message_size_too_large",
"category": "size",