: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ingestion): stamp group type mapping created_at from event timestamp (#64265)
Paweł Ledwońeb708b08d4f5
diff --git a/nodejs/src/ingestion/event-processing/groups.test.ts b/nodejs/src/ingestion/event-processing/groups.test.tsindex 06688f5c8931..140e17eb3f67 100644--- a/nodejs/src/ingestion/event-processing/groups.test.ts+++ b/nodejs/src/ingestion/event-processing/groups.test.ts@@ -1,3 +1,5 @@+import { DateTime } from 'luxon'+import { GroupTypeToColumnIndex, ProjectId } from '../../types'import { addGroupProperties, enrichPropertiesWithGroupTypes } from './groups'@@ -48,7 +50,15 @@ describe('addGroupProperties', () => {it('does nothing if no $groups present', async () => {const mgr = mockGroupTypeManager({ org: 0 })- expect(await addGroupProperties(2, 2 as ProjectId, { foo: 'bar' }, mgr as any)).toEqual({+ expect(+ await addGroupProperties(+ 2,+ 2 as ProjectId,+ { foo: 'bar' },+ mgr as any,+ DateTime.fromISO('2020-01-01T00:00:00.000Z', { zone: 'utc' })+ )+ ).toEqual({foo: 'bar',})expect(mgr.fetchGroupTypeIndex).not.toHaveBeenCalled()@@ -65,8 +75,9 @@ describe('addGroupProperties', () => {foobar: 'afsafa',},}+ const eventTimestamp = DateTime.fromISO('2020-01-01T00:00:00.000Z', { zone: 'utc' })- expect(await addGroupProperties(2, 2 as ProjectId, properties, mgr as any)).toEqual({+ expect(await addGroupProperties(2, 2 as ProjectId, properties, mgr as any, eventTimestamp)).toEqual({foo: 'bar',$groups: {organization: 'PostHog',@@ -77,8 +88,9 @@ describe('addGroupProperties', () => {$group_1: 'web',})- expect(mgr.fetchGroupTypeIndex).toHaveBeenCalledWith(2, 2, 'organization')- expect(mgr.fetchGroupTypeIndex).toHaveBeenCalledWith(2, 2, 'project')- expect(mgr.fetchGroupTypeIndex).toHaveBeenCalledWith(2, 2, 'foobar')+ // The event timestamp is threaded through so newly-created mappings get created_at = event time.+ expect(mgr.fetchGroupTypeIndex).toHaveBeenCalledWith(2, 2, 'organization', eventTimestamp)+ expect(mgr.fetchGroupTypeIndex).toHaveBeenCalledWith(2, 2, 'project', eventTimestamp)+ expect(mgr.fetchGroupTypeIndex).toHaveBeenCalledWith(2, 2, 'foobar', eventTimestamp)})})diff --git a/nodejs/src/ingestion/event-processing/groups.ts b/nodejs/src/ingestion/event-processing/groups.tsindex d103a65aae83..ddc0ece038f4 100644--- a/nodejs/src/ingestion/event-processing/groups.ts+++ b/nodejs/src/ingestion/event-processing/groups.ts@@ -1,3 +1,5 @@+import { DateTime } from 'luxon'+import { Properties } from '~/plugin-scaffold'import { GroupTypeToColumnIndex, ProjectId, TeamId } from '../../types'@@ -25,7 +27,8 @@ export async function addGroupProperties(teamId: TeamId,projectId: ProjectId,properties: Properties,- groupTypeManager: GroupTypeManager+ groupTypeManager: GroupTypeManager,+ eventTimestamp: DateTime): Promise<Properties> {const groups = properties.$groupsif (typeof groups !== 'object' || groups === null || Array.isArray(groups)) {@@ -33,7 +36,7 @@ export async function addGroupProperties(}const resolvedTypes: GroupTypeToColumnIndex = {}for (const [groupType] of Object.entries(groups)) {- const columnIndex = await groupTypeManager.fetchGroupTypeIndex(teamId, projectId, groupType)+ const columnIndex = await groupTypeManager.fetchGroupTypeIndex(teamId, projectId, groupType, eventTimestamp)if (columnIndex !== null) {resolvedTypes[groupType] = columnIndex}diff --git a/nodejs/src/ingestion/event-processing/process-groups-step.ts b/nodejs/src/ingestion/event-processing/process-groups-step.tsindex 2eaed71a622a..7e4ccdd285b9 100644--- a/nodejs/src/ingestion/event-processing/process-groups-step.ts+++ b/nodejs/src/ingestion/event-processing/process-groups-step.ts@@ -51,7 +51,8 @@ export function createProcessGroupsStep<TInput extends ProcessGroupsStepInput>(team.id,team.project_id,preparedEvent.properties,- groupTypeManager+ groupTypeManager,+ DateTime.fromISO(preparedEvent.timestamp))if (preparedEvent.event === '$groupidentify') {@@ -85,7 +86,14 @@ async function updateGroupsAndFirstEvent(if (preparedEvent.event === '$groupidentify') {const { $group_type: groupType, $group_set: groupPropertiesToSet } = preparedEvent.propertiesif (groupType != null && groupPropertiesToSet != null) {- promises.push(groupTypeManager.fetchGroupTypeIndex(team.id, team.project_id, groupType))+ promises.push(+ groupTypeManager.fetchGroupTypeIndex(+ team.id,+ team.project_id,+ groupType,+ DateTime.fromISO(preparedEvent.timestamp)+ )+ )}}@@ -105,7 +113,7 @@ async function upsertGroup(}const { $group_type: groupType, $group_key: groupKey, $group_set: groupPropertiesToSet } = properties- const groupTypeIndex = await groupTypeManager.fetchGroupTypeIndex(teamId, projectId, groupType)+ const groupTypeIndex = await groupTypeManager.fetchGroupTypeIndex(teamId, projectId, groupType, timestamp)if (groupTypeIndex !== null) {await groupStore.upsertGroup(teamId,diff --git a/nodejs/src/ingestion/personhog/personhog-group-repository.test.ts b/nodejs/src/ingestion/personhog/personhog-group-repository.test.tsindex 8bd8e128bb21..261319c691f7 100644--- a/nodejs/src/ingestion/personhog/personhog-group-repository.test.ts+++ b/nodejs/src/ingestion/personhog/personhog-group-repository.test.ts@@ -591,11 +591,12 @@ describe('PersonHogGroupRepository', () => {it('insertGroupType', async () => {mockPostgres.insertGroupType.mockResolvedValue([0 as GroupTypeIndex, true])const repo = createRepo(100)+ const createdAt = DateTime.fromISO('2020-01-01T00:00:00.000Z', { zone: 'utc' })- const result = await repo.insertGroupType(TEAM_ID, PROJECT_ID, 'organization', 0)+ const result = await repo.insertGroupType(TEAM_ID, PROJECT_ID, 'organization', 0, createdAt)expect(result).toEqual([0, true])- expect(mockPostgres.insertGroupType).toHaveBeenCalledWith(TEAM_ID, PROJECT_ID, 'organization', 0)+ expect(mockPostgres.insertGroupType).toHaveBeenCalledWith(TEAM_ID, PROJECT_ID, 'organization', 0, createdAt)})it('inTransaction', async () => {diff --git a/nodejs/src/ingestion/personhog/personhog-group-repository.ts b/nodejs/src/ingestion/personhog/personhog-group-repository.tsindex 4daa95c03271..b94fbcfd878e 100644--- a/nodejs/src/ingestion/personhog/personhog-group-repository.ts+++ b/nodejs/src/ingestion/personhog/personhog-group-repository.ts@@ -206,9 +206,10 @@ export class PersonHogGroupRepository implements GroupRepository {teamId: TeamId,projectId: ProjectId,groupType: string,- index: number+ index: number,+ createdAt: DateTime): Promise<[GroupTypeIndex | null, boolean]> {- return this.postgres.insertGroupType(teamId, projectId, groupType, index)+ return this.postgres.insertGroupType(teamId, projectId, groupType, index, createdAt)}inTransaction<T>(description: string, transaction: (tx: GroupRepositoryTransaction) => Promise<T>): Promise<T> {diff --git a/nodejs/src/ingestion/personhog/personhog-postgres-parity.test.ts b/nodejs/src/ingestion/personhog/personhog-postgres-parity.test.tsindex b38f72560936..83cbf7f20de6 100644--- a/nodejs/src/ingestion/personhog/personhog-postgres-parity.test.ts+++ b/nodejs/src/ingestion/personhog/personhog-postgres-parity.test.ts@@ -22,6 +22,8 @@ import { PersonHogClient } from './client'jest.mock('../../utils/logger')+const TEST_TIMESTAMP = DateTime.fromISO('2020-01-01T00:00:00.000Z', { zone: 'utc' })+const textEncoder = new TextEncoder()function jsonBytes(obj: unknown): Uint8Array {@@ -379,8 +381,8 @@ describe('PersonHog ↔ Postgres parity', () => {describe('fetchGroupTypesByTeamIds', () => {it('team with multiple group types produces identical output', async () => {- await postgresRepo.insertGroupType(teamId, projectId, 'company', 0)- await postgresRepo.insertGroupType(teamId, projectId, 'organization', 1)+ await postgresRepo.insertGroupType(teamId, projectId, 'company', 0, TEST_TIMESTAMP)+ await postgresRepo.insertGroupType(teamId, projectId, 'organization', 1, TEST_TIMESTAMP)const fromPostgres = await postgresRepo.fetchGroupTypesByTeamIds([teamId])@@ -425,7 +427,7 @@ describe('PersonHog ↔ Postgres parity', () => {const teamId2 = 10 as TeamIdawait insertTestTeam(teamId2)- await postgresRepo.insertGroupType(teamId, projectId, 'company', 0)+ await postgresRepo.insertGroupType(teamId, projectId, 'company', 0, TEST_TIMESTAMP)// teamId2 has no group typesconst fromPostgres = await postgresRepo.fetchGroupTypesByTeamIds([teamId, teamId2])@@ -465,7 +467,7 @@ describe('PersonHog ↔ Postgres parity', () => {describe('fetchGroupTypesByProjectIds', () => {it('project with group types produces identical output', async () => {- await postgresRepo.insertGroupType(teamId, projectId, 'workspace', 0)+ await postgresRepo.insertGroupType(teamId, projectId, 'workspace', 0, TEST_TIMESTAMP)const fromPostgres = await postgresRepo.fetchGroupTypesByProjectIds([projectId])diff --git a/nodejs/src/worker/ingestion/group-type-manager.test.ts b/nodejs/src/worker/ingestion/group-type-manager.test.tsindex 723cdc1816bd..8e5175a509bc 100644--- a/nodejs/src/worker/ingestion/group-type-manager.test.ts+++ b/nodejs/src/worker/ingestion/group-type-manager.test.ts@@ -1,3 +1,5 @@+import { DateTime } from 'luxon'+import { createTeam, getTeam, resetTestDatabase } from '../../../tests/helpers/sql'import { Hub, ProjectId, TeamId } from '../../types'import { closeHub, createHub } from '../../utils/db/hub'@@ -9,6 +11,8 @@ jest.mock('../../utils/posthog', () => ({captureTeamEvent: jest.fn(),}))+const TEST_TIMESTAMP = DateTime.fromISO('2020-01-01T00:00:00.000Z', { zone: 'utc' })+describe('GroupTypeManager()', () => {let hub: Hublet groupTypeManager: GroupTypeManager@@ -33,8 +37,8 @@ describe('GroupTypeManager()', () => {expect(groupTypes).toEqual({})jest.spyOn(global.Date, 'now').mockImplementation(() => new Date('2020-02-27 11:00:25').getTime())- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0)- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'bar', 1)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0, TEST_TIMESTAMP)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'bar', 1, TEST_TIMESTAMP)jest.mocked(hub.postgres.query).mockClear()@@ -56,20 +60,47 @@ describe('GroupTypeManager()', () => {it('fetches group types that have been inserted', async () => {expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({})- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g0', 0)).toEqual([0, true])- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g1', 1)).toEqual([1, true])+ expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g0', 0, TEST_TIMESTAMP)).toEqual([+ 0,+ true,+ ])+ expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g1', 1, TEST_TIMESTAMP)).toEqual([+ 1,+ true,+ ])groupTypeManager['loader'].markForRefresh('2')expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({ g0: 0, g1: 1 })})it('handles conflicting by index when inserting and limits', async () => {- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g0', 0)).toEqual([0, true])- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g1', 0)).toEqual([1, true])- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g2', 0)).toEqual([2, true])- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g3', 1)).toEqual([3, true])- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g4', 0)).toEqual([4, true])- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g5', 0)).toEqual([null, false])- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g6', 0)).toEqual([null, false])+ expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g0', 0, TEST_TIMESTAMP)).toEqual([+ 0,+ true,+ ])+ expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g1', 0, TEST_TIMESTAMP)).toEqual([+ 1,+ true,+ ])+ expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g2', 0, TEST_TIMESTAMP)).toEqual([+ 2,+ true,+ ])+ expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g3', 1, TEST_TIMESTAMP)).toEqual([+ 3,+ true,+ ])+ expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g4', 0, TEST_TIMESTAMP)).toEqual([+ 4,+ true,+ ])+ expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g5', 0, TEST_TIMESTAMP)).toEqual([+ null,+ false,+ ])+ expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g6', 0, TEST_TIMESTAMP)).toEqual([+ null,+ false,+ ])expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({g0: 0,@@ -81,11 +112,23 @@ describe('GroupTypeManager()', () => {})it('handles conflict by name when inserting', async () => {- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'group_name', 0)).toEqual([0, true])- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'group_name', 0)).toEqual([0, false])- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'group_name', 0)).toEqual([0, false])- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0)).toEqual([1, true])- expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0)).toEqual([1, false])+ expect(+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'group_name', 0, TEST_TIMESTAMP)+ ).toEqual([0, true])+ expect(+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'group_name', 0, TEST_TIMESTAMP)+ ).toEqual([0, false])+ expect(+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'group_name', 0, TEST_TIMESTAMP)+ ).toEqual([0, false])+ expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0, TEST_TIMESTAMP)).toEqual([+ 1,+ true,+ ])+ expect(await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0, TEST_TIMESTAMP)).toEqual([+ 1,+ false,+ ])expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({ group_name: 0, foo: 1 })})@@ -93,14 +136,14 @@ describe('GroupTypeManager()', () => {describe('fetchGroupTypeIndex()', () => {it('fetches an already existing value', async () => {- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0)- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'bar', 1)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0, TEST_TIMESTAMP)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'bar', 1, TEST_TIMESTAMP)jest.mocked(hub.postgres.query).mockClear()jest.mocked(hub.groupRepository.insertGroupType).mockClear()- expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'foo')).toEqual(0)- expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'bar')).toEqual(1)+ expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'foo', TEST_TIMESTAMP)).toEqual(0)+ expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'bar', TEST_TIMESTAMP)).toEqual(1)expect(hub.postgres.query).toHaveBeenCalledTimes(1)expect(hub.groupRepository.insertGroupType).toHaveBeenCalledTimes(0)@@ -108,12 +151,12 @@ describe('GroupTypeManager()', () => {})it('inserts value if it does not exist yet at next index, resets cache', async () => {- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0, TEST_TIMESTAMP)jest.mocked(hub.groupRepository.insertGroupType).mockClear()jest.mocked(hub.postgres.query).mockClear()- expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'second')).toEqual(1)+ expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'second', TEST_TIMESTAMP)).toEqual(1)expect(hub.groupRepository.insertGroupType).toHaveBeenCalledTimes(1)expect(hub.postgres.query).toHaveBeenCalledTimes(3) // FETCH + INSERT + Team lookup@@ -128,7 +171,7 @@ describe('GroupTypeManager()', () => {})- expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'third')).toEqual(2)+ expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'third', TEST_TIMESTAMP)).toEqual(2)jest.mocked(hub.postgres.query).mockClear()expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({@@ -136,8 +179,8 @@ describe('GroupTypeManager()', () => {second: 1,third: 2,})- expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'second')).toEqual(1)- expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'third')).toEqual(2)+ expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'second', TEST_TIMESTAMP)).toEqual(1)+ expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'third', TEST_TIMESTAMP)).toEqual(2)expect(hub.postgres.query).toHaveBeenCalledTimes(1)})@@ -145,8 +188,8 @@ describe('GroupTypeManager()', () => {it('handles raciness for inserting a new group', async () => {expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({})- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0) // Emulate another thread inserting foo- expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'second')).toEqual(1)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0, TEST_TIMESTAMP) // Emulate another thread inserting foo+ expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'second', TEST_TIMESTAMP)).toEqual(1)expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({foo: 0,second: 1,@@ -157,10 +200,10 @@ describe('GroupTypeManager()', () => {expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({})// Emulate another thread inserting group types, with both team and project the same- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0)- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'bar', 0)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0, TEST_TIMESTAMP)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'bar', 0, TEST_TIMESTAMP)- expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'bar')).toEqual(1)+ expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'bar', TEST_TIMESTAMP)).toEqual(1)expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({foo: 0,bar: 1,@@ -173,10 +216,10 @@ describe('GroupTypeManager()', () => {expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({})// Emulate another thread inserting group types, with the project the same- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0)- await hub.groupRepository.insertGroupType(otherTeamId, 2 as ProjectId, 'bar', 0)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0, TEST_TIMESTAMP)+ await hub.groupRepository.insertGroupType(otherTeamId, 2 as ProjectId, 'bar', 0, TEST_TIMESTAMP)- expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'bar')).toEqual(1)+ expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'bar', TEST_TIMESTAMP)).toEqual(1)expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({foo: 0,bar: 1,@@ -184,13 +227,13 @@ describe('GroupTypeManager()', () => {})it('returns null once limit is met', async () => {- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g0', 0)- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g1', 1)- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g2', 2)- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g3', 3)- await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g4', 4)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g0', 0, TEST_TIMESTAMP)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g1', 1, TEST_TIMESTAMP)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g2', 2, TEST_TIMESTAMP)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g3', 3, TEST_TIMESTAMP)+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g4', 4, TEST_TIMESTAMP)- expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'new')).toEqual(null)+ expect(await groupTypeManager.fetchGroupTypeIndex(2, 2 as ProjectId, 'new', TEST_TIMESTAMP)).toEqual(null)expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({g0: 0,g1: 1,@@ -200,12 +243,28 @@ describe('GroupTypeManager()', () => {})})+ it('stamps created_at from the provided event timestamp', async () => {+ const eventTimestamp = DateTime.fromISO('2020-01-01T00:00:00.000Z', { zone: 'utc' })++ expect(+ await groupTypeManager.fetchGroupTypeIndex(2 as TeamId, 2 as ProjectId, 'foo', eventTimestamp)+ ).toEqual(0)++ const { rows } = await hub.postgres.query(+ PostgresUse.PERSONS_WRITE,+ "SELECT created_at FROM posthog_grouptypemapping WHERE project_id = 2 AND group_type = 'foo'",+ undefined,+ 'fetchCreatedAt'+ )+ expect(DateTime.fromISO(rows[0].created_at).toMillis()).toEqual(eventTimestamp.toMillis())+ })+it('uses next available index after a group type is deleted', async () => {- await hub.groupRepository.insertGroupType(2 as TeamId, 2 as ProjectId, 'A', 0)- await hub.groupRepository.insertGroupType(2 as TeamId, 2 as ProjectId, 'B', 1)- await hub.groupRepository.insertGroupType(2 as TeamId, 2 as ProjectId, 'C', 2)- await hub.groupRepository.insertGroupType(2 as TeamId, 2 as ProjectId, 'D', 3)- await hub.groupRepository.insertGroupType(2 as TeamId, 2 as ProjectId, 'E', 4)+ await hub.groupRepository.insertGroupType(2 as TeamId, 2 as ProjectId, 'A', 0, TEST_TIMESTAMP)+ await hub.groupRepository.insertGroupType(2 as TeamId, 2 as ProjectId, 'B', 1, TEST_TIMESTAMP)+ await hub.groupRepository.insertGroupType(2 as TeamId, 2 as ProjectId, 'C', 2, TEST_TIMESTAMP)+ await hub.groupRepository.insertGroupType(2 as TeamId, 2 as ProjectId, 'D', 3, TEST_TIMESTAMP)+ await hub.groupRepository.insertGroupType(2 as TeamId, 2 as ProjectId, 'E', 4, TEST_TIMESTAMP)// Simulate deleting group type E (@ index 4). this is normally performed by a// Django API endpoint which involves cache-busting, too. (we'll manually do this later)@@ -225,7 +284,9 @@ describe('GroupTypeManager()', () => {})// Creating a new group type F should get index 4 (the now-free slot at the end)- expect(await groupTypeManager.fetchGroupTypeIndex(2 as TeamId, 2 as ProjectId, 'F')).toEqual(4)+ expect(+ await groupTypeManager.fetchGroupTypeIndex(2 as TeamId, 2 as ProjectId, 'F', TEST_TIMESTAMP)+ ).toEqual(4)expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({A: 0,B: 1,@@ -253,7 +314,9 @@ describe('GroupTypeManager()', () => {})// Creating a new group type G should get index 2 (the now-free slot)- expect(await groupTypeManager.fetchGroupTypeIndex(2 as TeamId, 2 as ProjectId, 'G')).toEqual(2)+ expect(+ await groupTypeManager.fetchGroupTypeIndex(2 as TeamId, 2 as ProjectId, 'G', TEST_TIMESTAMP)+ ).toEqual(2)expect(await groupTypeManager.fetchGroupTypes(2 as ProjectId)).toEqual({A: 0,B: 1,diff --git a/nodejs/src/worker/ingestion/group-type-manager.ts b/nodejs/src/worker/ingestion/group-type-manager.tsindex 2c39e681837e..415f7a215686 100644--- a/nodejs/src/worker/ingestion/group-type-manager.ts+++ b/nodejs/src/worker/ingestion/group-type-manager.ts@@ -1,3 +1,5 @@+import { DateTime } from 'luxon'+import { GroupTypeIndex, GroupTypeToColumnIndex, GroupTypesByProjectId, ProjectId, Team, TeamId } from '../../types'import { timeoutGuard } from '../../utils/db/utils'import { LazyLoader } from '../../utils/lazy-loader'@@ -56,7 +58,8 @@ export class GroupTypeManager {public async fetchGroupTypeIndex(teamId: TeamId,projectId: ProjectId,- groupType: string+ groupType: string,+ eventTimestamp: DateTime): Promise<GroupTypeIndex | null> {const groupTypes = await this.fetchGroupTypes(projectId)if (groupType in groupTypes) {@@ -73,11 +76,14 @@ export class GroupTypeManager {nextAvailableIndex++}+ // Use the triggering event's timestamp as the mapping's created_at, so historical imports+ // register the group type as of the event rather than wall-clock now (which would mask them).const [groupTypeIndex, isInsert] = await this.groupRepository.insertGroupType(teamId,projectId,groupType,- nextAvailableIndex+ nextAvailableIndex,+ eventTimestamp)if (groupTypeIndex !== null) {this.loader.markForRefresh(projectId.toString())diff --git a/nodejs/src/worker/ingestion/groups/repositories/group-repository-transaction.interface.ts b/nodejs/src/worker/ingestion/groups/repositories/group-repository-transaction.interface.tsindex 6b860d8a6253..7fe8d99dae50 100644--- a/nodejs/src/worker/ingestion/groups/repositories/group-repository-transaction.interface.ts+++ b/nodejs/src/worker/ingestion/groups/repositories/group-repository-transaction.interface.ts@@ -67,6 +67,7 @@ export interface GroupRepositoryTransaction {teamId: TeamId,projectId: ProjectId,groupType: string,- index: number+ index: number,+ createdAt: DateTime): Promise<[GroupTypeIndex | null, boolean]>}diff --git a/nodejs/src/worker/ingestion/groups/repositories/group-repository.interface.ts b/nodejs/src/worker/ingestion/groups/repositories/group-repository.interface.tsindex adf7f37219f2..f717e774f8d8 100644--- a/nodejs/src/worker/ingestion/groups/repositories/group-repository.interface.ts+++ b/nodejs/src/worker/ingestion/groups/repositories/group-repository.interface.ts@@ -119,7 +119,8 @@ export interface GroupRepository {teamId: TeamId,projectId: ProjectId,groupType: string,- index: number+ index: number,+ createdAt: DateTime): Promise<[GroupTypeIndex | null, boolean]>// Transaction Methodsdiff --git a/nodejs/src/worker/ingestion/groups/repositories/postgres-group-repository-transaction.ts b/nodejs/src/worker/ingestion/groups/repositories/postgres-group-repository-transaction.tsindex e4b12cd95df5..91fe00365058 100644--- a/nodejs/src/worker/ingestion/groups/repositories/postgres-group-repository-transaction.ts+++ b/nodejs/src/worker/ingestion/groups/repositories/postgres-group-repository-transaction.ts@@ -104,8 +104,9 @@ export class PostgresGroupRepositoryTransaction implements GroupRepositoryTransateamId: TeamId,projectId: ProjectId,groupType: string,- index: number+ index: number,+ createdAt: DateTime): Promise<[GroupTypeIndex | null, boolean]> {- return await this.repository.insertGroupType(teamId, projectId, groupType, index, this.tx)+ return await this.repository.insertGroupType(teamId, projectId, groupType, index, createdAt, this.tx)}}diff --git a/nodejs/src/worker/ingestion/groups/repositories/postgres-group-repository.integration.test.ts b/nodejs/src/worker/ingestion/groups/repositories/postgres-group-repository.integration.test.tsindex 2989ea75f770..24de84fb81bb 100644--- a/nodejs/src/worker/ingestion/groups/repositories/postgres-group-repository.integration.test.ts+++ b/nodejs/src/worker/ingestion/groups/repositories/postgres-group-repository.integration.test.ts@@ -15,6 +15,8 @@ import { PostgresRouter, PostgresUse } from '../../../../utils/db/postgres'import { UUIDT } from '../../../../utils/utils'import { PostgresGroupRepository } from './postgres-group-repository'+const TEST_TIMESTAMP = DateTime.fromISO('2020-01-01T00:00:00.000Z', { zone: 'utc' })+describe('PostgresGroupRepository Integration', () => {let hub: Hublet repository: PostgresGroupRepository@@ -1293,7 +1295,8 @@ describe('PostgresGroupRepository Integration', () => {teamId,teamId as ProjectId, // insertTestTeam creates project with id = teamId'company',- 0+ 0,+ TEST_TIMESTAMP)expect(groupTypeIndex).toBe(0)@@ -1318,14 +1321,15 @@ describe('PostgresGroupRepository Integration', () => {await insertTestTeam(teamId)// Insert the group type first- await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0)+ await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0, TEST_TIMESTAMP)// Try to insert the same group type againconst [groupTypeIndex, isInsert] = await repository.insertGroupType(teamId,teamId as ProjectId,'company',- 0+ 0,+ TEST_TIMESTAMP)expect(groupTypeIndex).toBe(0)@@ -1346,17 +1350,35 @@ describe('PostgresGroupRepository Integration', () => {await insertTestTeam(teamId)// Insert first group type at index 0- const [index1, isInsert1] = await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0)+ const [index1, isInsert1] = await repository.insertGroupType(+ teamId,+ teamId as ProjectId,+ 'company',+ 0,+ TEST_TIMESTAMP+ )expect(index1).toBe(0)expect(isInsert1).toBe(true)// Try to insert second group type at index 0 (should get index 1)- const [index2, isInsert2] = await repository.insertGroupType(teamId, teamId as ProjectId, 'organization', 0)+ const [index2, isInsert2] = await repository.insertGroupType(+ teamId,+ teamId as ProjectId,+ 'organization',+ 0,+ TEST_TIMESTAMP+ )expect(index2).toBe(1)expect(isInsert2).toBe(true)// Try to insert third group type at index 0 (should get index 2)- const [index3, isInsert3] = await repository.insertGroupType(teamId, teamId as ProjectId, 'team', 0)+ const [index3, isInsert3] = await repository.insertGroupType(+ teamId,+ teamId as ProjectId,+ 'team',+ 0,+ TEST_TIMESTAMP+ )expect(index3).toBe(2)expect(isInsert3).toBe(true)})@@ -1370,14 +1392,21 @@ describe('PostgresGroupRepository Integration', () => {teamId,teamId as ProjectId,`group_type_${i}`,- i+ i,+ TEST_TIMESTAMP)expect(index).toBe(i)expect(isInsert).toBe(true)}// Try to insert the 6th group type (should fail)- const [index6, isInsert6] = await repository.insertGroupType(teamId, teamId as ProjectId, 'group_type_6', 5)+ const [index6, isInsert6] = await repository.insertGroupType(+ teamId,+ teamId as ProjectId,+ 'group_type_6',+ 5,+ TEST_TIMESTAMP+ )expect(index6).toBe(null)expect(isInsert6).toBe(false)})@@ -1393,7 +1422,8 @@ describe('PostgresGroupRepository Integration', () => {localTeamId1,localTeamId1 as ProjectId,'company',- 0+ 0,+ TEST_TIMESTAMP)expect(index1).toBe(0)expect(isInsert1).toBe(true)@@ -1403,7 +1433,8 @@ describe('PostgresGroupRepository Integration', () => {localTeamId2,localTeamId2 as ProjectId,'company',- 0+ 0,+ TEST_TIMESTAMP)expect(index2).toBe(0)expect(isInsert2).toBe(true)@@ -1445,7 +1476,8 @@ describe('PostgresGroupRepository Integration', () => {teamId,teamId as ProjectId,'company',- 0+ 0,+ TEST_TIMESTAMP)expect(groupTypeIndex).toBe(0)@@ -1456,7 +1488,7 @@ describe('PostgresGroupRepository Integration', () => {await insertTestTeam(teamId)const result = await repository.inTransaction('test insertGroupType transaction', async (tx) => {- return await tx.insertGroupType(teamId, teamId as ProjectId, 'company', 0)+ return await tx.insertGroupType(teamId, teamId as ProjectId, 'company', 0, TEST_TIMESTAMP)})expect(result).toEqual([0, true])@@ -1476,7 +1508,7 @@ describe('PostgresGroupRepository Integration', () => {await insertTestTeam(teamId)const result = await repository.inRawTransaction('test insertGroupType raw transaction', async (tx) => {- return await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0, tx)+ return await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0, TEST_TIMESTAMP, tx)})expect(result).toEqual([0, true])@@ -1499,7 +1531,7 @@ describe('PostgresGroupRepository Integration', () => {await expect(repository.inTransaction('failing insertGroupType transaction', async (tx) => {// Insert a group type- await tx.insertGroupType(teamId, teamId as ProjectId, 'company', 0)+ await tx.insertGroupType(teamId, teamId as ProjectId, 'company', 0, TEST_TIMESTAMP)// This should cause the transaction to rollbackthrow new Error('Simulated transaction failure')@@ -1526,7 +1558,8 @@ describe('PostgresGroupRepository Integration', () => {teamId,teamId as ProjectId,specialGroupType,- 0+ 0,+ TEST_TIMESTAMP)expect(groupTypeIndex).toBe(0)@@ -1553,7 +1586,8 @@ describe('PostgresGroupRepository Integration', () => {teamId,teamId as ProjectId,emptyGroupType,- 0+ 0,+ TEST_TIMESTAMP)expect(groupTypeIndex).toBe(0)@@ -1580,7 +1614,8 @@ describe('PostgresGroupRepository Integration', () => {teamId,teamId as ProjectId,longGroupType,- 0+ 0,+ TEST_TIMESTAMP)expect(groupTypeIndex).toBe(0)@@ -1625,8 +1660,8 @@ describe('PostgresGroupRepository Integration', () => {await insertTestTeam(teamId)// Insert some group types- await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0)- await repository.insertGroupType(teamId, teamId as ProjectId, 'organization', 1)+ await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0, TEST_TIMESTAMP)+ await repository.insertGroupType(teamId, teamId as ProjectId, 'organization', 1, TEST_TIMESTAMP)const result = await repository.fetchGroupTypesByProjectIds([teamId as ProjectId])@@ -1645,11 +1680,11 @@ describe('PostgresGroupRepository Integration', () => {await insertTestTeam(localTeamId2)// Insert group types for first project- await repository.insertGroupType(localTeamId1, localTeamId1 as ProjectId, 'company', 0)- await repository.insertGroupType(localTeamId1, localTeamId1 as ProjectId, 'team', 1)+ await repository.insertGroupType(localTeamId1, localTeamId1 as ProjectId, 'company', 0, TEST_TIMESTAMP)+ await repository.insertGroupType(localTeamId1, localTeamId1 as ProjectId, 'team', 1, TEST_TIMESTAMP)// Insert group types for second project- await repository.insertGroupType(localTeamId2, localTeamId2 as ProjectId, 'organization', 0)+ await repository.insertGroupType(localTeamId2, localTeamId2 as ProjectId, 'organization', 0, TEST_TIMESTAMP)const result = await repository.fetchGroupTypesByProjectIds([localTeamId1 as ProjectId,@@ -1672,7 +1707,7 @@ describe('PostgresGroupRepository Integration', () => {await insertTestTeam(localTeamId2)// Only insert group types for first project- await repository.insertGroupType(localTeamId1, localTeamId1 as ProjectId, 'company', 0)+ await repository.insertGroupType(localTeamId1, localTeamId1 as ProjectId, 'company', 0, TEST_TIMESTAMP)const result = await repository.fetchGroupTypesByProjectIds([localTeamId1 as ProjectId,@@ -1687,7 +1722,7 @@ describe('PostgresGroupRepository Integration', () => {it('should return correct types for group_type_index', async () => {await insertTestTeam(teamId)- await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0)+ await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0, TEST_TIMESTAMP)const result = await repository.fetchGroupTypesByProjectIds([teamId as ProjectId])@@ -1720,8 +1755,8 @@ describe('PostgresGroupRepository Integration', () => {await insertTestTeam(teamId)// Insert some group types- await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0)- await repository.insertGroupType(teamId, teamId as ProjectId, 'organization', 1)+ await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0, TEST_TIMESTAMP)+ await repository.insertGroupType(teamId, teamId as ProjectId, 'organization', 1, TEST_TIMESTAMP)const result = await repository.fetchGroupTypesByTeamIds([teamId])@@ -1740,11 +1775,11 @@ describe('PostgresGroupRepository Integration', () => {await insertTestTeam(localTeamId2)// Insert group types for first team- await repository.insertGroupType(localTeamId1, localTeamId1 as ProjectId, 'company', 0)- await repository.insertGroupType(localTeamId1, localTeamId1 as ProjectId, 'team', 1)+ await repository.insertGroupType(localTeamId1, localTeamId1 as ProjectId, 'company', 0, TEST_TIMESTAMP)+ await repository.insertGroupType(localTeamId1, localTeamId1 as ProjectId, 'team', 1, TEST_TIMESTAMP)// Insert group types for second team- await repository.insertGroupType(localTeamId2, localTeamId2 as ProjectId, 'organization', 0)+ await repository.insertGroupType(localTeamId2, localTeamId2 as ProjectId, 'organization', 0, TEST_TIMESTAMP)const result = await repository.fetchGroupTypesByTeamIds([localTeamId1, localTeamId2])@@ -1764,7 +1799,7 @@ describe('PostgresGroupRepository Integration', () => {await insertTestTeam(localTeamId2)// Only insert group types for first team- await repository.insertGroupType(localTeamId1, localTeamId1 as ProjectId, 'company', 0)+ await repository.insertGroupType(localTeamId1, localTeamId1 as ProjectId, 'company', 0, TEST_TIMESTAMP)const result = await repository.fetchGroupTypesByTeamIds([localTeamId1, localTeamId2])@@ -1776,7 +1811,7 @@ describe('PostgresGroupRepository Integration', () => {it('should return correct types for group_type_index', async () => {await insertTestTeam(teamId)- await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0)+ await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0, TEST_TIMESTAMP)const result = await repository.fetchGroupTypesByTeamIds([teamId])@@ -1790,8 +1825,8 @@ describe('PostgresGroupRepository Integration', () => {beforeEach(async () => {await insertTestTeam(teamId)// Insert group types- await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0)- await repository.insertGroupType(teamId, teamId as ProjectId, 'organization', 1)+ await repository.insertGroupType(teamId, teamId as ProjectId, 'company', 0, TEST_TIMESTAMP)+ await repository.insertGroupType(teamId, teamId as ProjectId, 'organization', 1, TEST_TIMESTAMP)})it('should return empty array for empty inputs', async () => {@@ -1909,7 +1944,7 @@ describe('PostgresGroupRepository Integration', () => {it('should handle multiple teams', async () => {const localTeamId2 = 25 as TeamIdawait insertTestTeam(localTeamId2)- await repository.insertGroupType(localTeamId2, localTeamId2 as ProjectId, 'company', 0)+ await repository.insertGroupType(localTeamId2, localTeamId2 as ProjectId, 'company', 0, TEST_TIMESTAMP)const team1Props = { name: 'Team 1 Company' }const team2Props = { name: 'Team 2 Company' }diff --git a/nodejs/src/worker/ingestion/groups/repositories/postgres-group-repository.ts b/nodejs/src/worker/ingestion/groups/repositories/postgres-group-repository.tsindex 359f6863c620..04c25a76f417 100644--- a/nodejs/src/worker/ingestion/groups/repositories/postgres-group-repository.ts+++ b/nodejs/src/worker/ingestion/groups/repositories/postgres-group-repository.ts@@ -331,12 +331,15 @@ export class PostgresGroupRepositoryprojectId: ProjectId,groupType: string,index: number,+ createdAt: DateTime,tx?: TransactionClient): Promise<[GroupTypeIndex | null, boolean]> {if (index < 0 || index >= MAX_GROUP_TYPES_PER_TEAM) {return [null, false]}+ // created_at is stamped from the triggering event's timestamp so historical imports don't get a+ // wall-clock date that postdates their events — HogQL masks $group_N for events older than this.const insertGroupTypeResult = await this.postgres.query(tx ?? PostgresUse.PERSONS_WRITE,`@@ -350,12 +353,12 @@ export class PostgresGroupRepositoryUNIONSELECT group_type_index, 0 AS is_insert FROM posthog_grouptypemapping WHERE project_id = $2 AND group_type = $3;`,- [teamId, projectId, groupType, index, new Date()],+ [teamId, projectId, groupType, index, createdAt.toISO()],'insertGroupType')if (insertGroupTypeResult.rows.length == 0) {- return await this.insertGroupType(teamId, projectId, groupType, index + 1, tx)+ return await this.insertGroupType(teamId, projectId, groupType, index + 1, createdAt, tx)}const { group_type_index, is_insert } = insertGroupTypeResult.rows[0]diff --git a/nodejs/src/worker/ingestion/groups/repositories/raw-postgres-group-repository.interface.ts b/nodejs/src/worker/ingestion/groups/repositories/raw-postgres-group-repository.interface.tsindex 720d89c385c0..7a1804889ceb 100644--- a/nodejs/src/worker/ingestion/groups/repositories/raw-postgres-group-repository.interface.ts+++ b/nodejs/src/worker/ingestion/groups/repositories/raw-postgres-group-repository.interface.ts@@ -89,6 +89,7 @@ export interface RawPostgresGroupRepository {projectId: ProjectId,groupType: string,index: number,+ createdAt: DateTime,tx?: TransactionClient): Promise<[GroupTypeIndex | null, boolean]>