: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
feat(ingestion): batch group creations, default batched updates on (#73071)
José Sequeiraee799e635a92
diff --git a/nodejs/src/common/groups/repositories/group-repository.interface.ts b/nodejs/src/common/groups/repositories/group-repository.interface.tsindex a82846706aac..c256cf956873 100644--- a/nodejs/src/common/groups/repositories/group-repository.interface.ts+++ b/nodejs/src/common/groups/repositories/group-repository.interface.ts@@ -57,6 +57,21 @@ export interface GroupPropertiesToSetUpdate {createdAt: DateTime}+/** A batched group creation: one new row at version 1 per entry. */+export interface GroupCreate {+ teamId: TeamId+ groupTypeIndex: GroupTypeIndex+ groupKey: string+ groupProperties: Properties+ createdAt: DateTime+}++/**+ * Result row of insertGroupsBatch: `inserted` is false when the row already+ * existed and the creation's properties were merged onto it instead.+ */+export type GroupCreateResult = Group & { inserted: boolean }+/*** Full group repository with read and write operations. Used by the* ingestion pipeline which creates, updates, and manages groups.@@ -91,6 +106,16 @@ export interface GroupRepository {*/updateGroupsBatch(updates: GroupPropertiesToSetUpdate[]): Promise<Group[]>+ /**+ * Inserts all groups in a single statement and returns one row per input.+ * Rows that already exist (a lost cross-pod race) are merged server-side+ * with the same jsonb semantics as updateGroupsBatch and come back with+ * `inserted: false`, so callers can tell creations from merges without a+ * second round trip. Creates must be unique by (team, type, key) —+ * duplicates make the whole statement fail.+ */+ insertGroupsBatch(creates: GroupCreate[]): Promise<GroupCreateResult[]>+insertGroup(teamId: TeamId,groupTypeIndex: GroupTypeIndex,diff --git a/nodejs/src/common/groups/repositories/postgres-group-repository.integration.test.ts b/nodejs/src/common/groups/repositories/postgres-group-repository.integration.test.tsindex 3cbb6e5b0aec..dcf9213871f6 100644--- a/nodejs/src/common/groups/repositories/postgres-group-repository.integration.test.ts+++ b/nodejs/src/common/groups/repositories/postgres-group-repository.integration.test.ts@@ -910,6 +910,57 @@ describe('PostgresGroupRepository Integration', () => {})})+ describe('insertGroupsBatch', () => {+ it('inserts new rows at version 1 and merges onto existing rows, flagging which happened', async () => {+ await insertTestTeam(teamId)+ await insertTestGroup({ version: 3 })++ const result = await repository.insertGroupsBatch([+ { teamId, groupTypeIndex, groupKey: 'new-a', groupProperties: { name: 'A' }, createdAt },+ {+ teamId,+ groupTypeIndex: 1 as GroupTypeIndex,+ groupKey: 'new-b',+ groupProperties: { plan: 'scale' },+ createdAt: createdAt.plus({ days: 1 }),+ },+ { teamId, groupTypeIndex, groupKey, groupProperties: { added: true }, createdAt },+ ])++ // One row per input: fresh inserts flagged true, the lost race+ // merged server-side and flagged false.+ expect(result).toHaveLength(3)+ const byKey = new Map(result.map((g) => [g.group_key, g]))+ expect(byKey.get('new-a')).toMatchObject({+ team_id: teamId,+ group_type_index: groupTypeIndex,+ group_properties: { name: 'A' },+ created_at: createdAt,+ version: 1,+ inserted: true,+ })+ expect(byKey.get('new-b')).toMatchObject({+ group_type_index: 1,+ group_properties: { plan: 'scale' },+ created_at: createdAt.plus({ days: 1 }),+ version: 1,+ inserted: true,+ })+ expect(byKey.get(groupKey)).toMatchObject({+ group_properties: { ...groupProperties, added: true },+ created_at: createdAt,+ version: 4,+ inserted: false,+ })++ // Both outcomes are persisted.+ const persisted = await repository.fetchGroup(teamId, groupTypeIndex, 'new-a')+ expect(persisted).toMatchObject({ group_properties: { name: 'A' }, version: 1 })+ const merged = await repository.fetchGroup(teamId, groupTypeIndex, groupKey)+ expect(merged).toMatchObject({ group_properties: { ...groupProperties, added: true }, version: 4 })+ })+ })+describe('inTransaction', () => {it('should execute operations within a transaction', async () => {await insertTestTeam(teamId)diff --git a/nodejs/src/common/groups/repositories/postgres-group-repository.ts b/nodejs/src/common/groups/repositories/postgres-group-repository.tsindex a20004f016e5..3332d5c5b5e7 100644--- a/nodejs/src/common/groups/repositories/postgres-group-repository.ts+++ b/nodejs/src/common/groups/repositories/postgres-group-repository.ts@@ -16,7 +16,13 @@ import {} from '~/types'import { GroupRepositoryTransaction } from './group-repository-transaction.interface'-import { GroupKey, GroupPropertiesToSetUpdate, GroupRepository } from './group-repository.interface'+import {+ GroupCreate,+ GroupCreateResult,+ GroupKey,+ GroupPropertiesToSetUpdate,+ GroupRepository,+} from './group-repository.interface'import { PostgresGroupRepositoryTransaction } from './postgres-group-repository-transaction'import { RawPostgresGroupRepository } from './raw-postgres-group-repository.interface'@@ -173,6 +179,62 @@ export class PostgresGroupRepositoryreturn rows.map((row) => this.toGroup(row))}+ async insertGroupsBatch(creates: GroupCreate[]): Promise<GroupCreateResult[]> {+ if (creates.length === 0) {+ return []+ }++ // Sort by row identity for the same cross-pod lock-ordering hygiene as+ // updateGroupsBatch. UNNEST keeps the statement shape constant for+ // prepared-statement reuse.+ const sortedCreates = [...creates].sort(+ (a, b) => a.teamId - b.teamId || a.groupTypeIndex - b.groupTypeIndex || a.groupKey.localeCompare(b.groupKey)+ )++ const teamIds: number[] = []+ const groupTypeIndexes: number[] = []+ const groupKeys: string[] = []+ const groupProperties: string[] = []+ const createdAts: string[] = []++ for (const create of sortedCreates) {+ teamIds.push(create.teamId)+ groupTypeIndexes.push(create.groupTypeIndex)+ groupKeys.push(create.groupKey)+ groupProperties.push(sanitizeJsonbValue(create.groupProperties))+ createdAts.push(create.createdAt.toISO()!)+ }++ // Rows that already exist (a lost cross-pod race) are merged in the+ // same statement with updateGroupsBatch's jsonb semantics, so callers+ // never need a second round trip to converge. `xmax = 0` is the+ // standard idiom for telling fresh inserts from conflict-updates:+ // an updated row carries the locking transaction's xid there.+ const { rows } = await this.postgres.query<RawGroup & { inserted: boolean }>(+ PostgresUse.PERSONS_WRITE,+ `+ INSERT INTO posthog_group AS g (team_id, group_key, group_type_index, group_properties, created_at, properties_last_updated_at, properties_last_operation, version)+ SELECT batch_team_id, batch_group_key, batch_group_type_index, new_properties::jsonb, new_created_at::timestamp with time zone, '{}'::jsonb, '{}'::jsonb, 1+ FROM UNNEST(+ $1::int[],+ $2::int[],+ $3::text[],+ $4::text[],+ $5::text[]+ ) AS batch(batch_team_id, batch_group_type_index, batch_group_key, new_properties, new_created_at)+ ON CONFLICT (team_id, group_key, group_type_index) DO UPDATE SET+ group_properties = COALESCE(g.group_properties, '{}'::jsonb) || EXCLUDED.group_properties,+ created_at = LEAST(g.created_at, EXCLUDED.created_at),+ version = COALESCE(g.version, 0)::numeric + 1+ RETURNING g.*, (g.xmax = 0) AS inserted+ `,+ [teamIds, groupTypeIndexes, groupKeys, groupProperties, createdAts],+ 'insertGroupsBatch'+ )++ return rows.map(({ inserted, ...row }) => ({ ...this.toGroup(row), inserted }))+ }+async insertGroup(teamId: TeamId,groupTypeIndex: GroupTypeIndex,diff --git a/nodejs/src/common/personhog/personhog-group-repository.test.ts b/nodejs/src/common/personhog/personhog-group-repository.test.tsindex ecaea43f382a..8bd724498bf3 100644--- a/nodejs/src/common/personhog/personhog-group-repository.test.ts+++ b/nodejs/src/common/personhog/personhog-group-repository.test.ts@@ -99,6 +99,7 @@ function createMockPostgres(): jest.Mocked<GroupRepository> {fetchGroupTypesByProjectIds: jest.fn(),insertGroup: jest.fn(),updateGroupsBatch: jest.fn(),+ insertGroupsBatch: jest.fn(),updateGroup: jest.fn(),updateGroupOptimistically: jest.fn(),insertGroupType: jest.fn(),diff --git a/nodejs/src/common/personhog/personhog-group-repository.ts b/nodejs/src/common/personhog/personhog-group-repository.tsindex 0eee6234de80..2ffdf0e7cbe1 100644--- a/nodejs/src/common/personhog/personhog-group-repository.ts+++ b/nodejs/src/common/personhog/personhog-group-repository.ts@@ -2,6 +2,8 @@ import { DateTime } from 'luxon'import { GroupRepositoryTransaction } from '~/common/groups/repositories/group-repository-transaction.interface'import {+ GroupCreate,+ GroupCreateResult,GroupKey,GroupPropertiesToSetUpdate,GroupRepository,@@ -194,6 +196,10 @@ export class PersonHogGroupRepository implements GroupRepository {return this.postgres.updateGroupsBatch(updates)}+ insertGroupsBatch(creates: GroupCreate[]): Promise<GroupCreateResult[]> {+ return this.postgres.insertGroupsBatch(creates)+ }+updateGroupOptimistically(teamId: TeamId,groupTypeIndex: GroupTypeIndex,diff --git a/nodejs/src/ingestion/common/groups/batch-writing-group-store.test.ts b/nodejs/src/ingestion/common/groups/batch-writing-group-store.test.tsindex 0dd9cf6fa310..4c47f5b75899 100644--- a/nodejs/src/ingestion/common/groups/batch-writing-group-store.test.ts+++ b/nodejs/src/ingestion/common/groups/batch-writing-group-store.test.ts@@ -8,7 +8,7 @@ import { RaceConditionError } from '~/common/utils/utils'import { BatchWritingGroupStore } from './batch-writing-group-store'import { groupCacheOperationsCounter } from './metrics'import { ClickhouseGroupRepository } from '~/common/groups/repositories/clickhouse-group-repository'-import { GroupRepository } from '~/common/groups/repositories/group-repository.interface'+import { GroupCreateResult, GroupRepository } from '~/common/groups/repositories/group-repository.interface'import { GroupsOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'@@ -49,6 +49,7 @@ describe('BatchWritingGroupStore', () => {}),fetchGroupsByKeys: jest.fn().mockResolvedValue([]),updateGroupsBatch: jest.fn().mockResolvedValue([]),+ insertGroupsBatch: jest.fn().mockResolvedValue([]),insertGroup: jest.fn().mockImplementation(() => {return Promise.resolve(1)}),@@ -106,7 +107,12 @@ describe('BatchWritingGroupStore', () => {clickhouseGroupRepository = new ClickhouseGroupRepository({queueMessages: mockQueueMessages,} as unknown as IngestionOutputs<GroupsOutput>)- groupStore = new BatchWritingGroupStore(groupRepository, clickhouseGroupRepository)+ // Pin the individual CAS flush path: it remains the fallback for+ // missing rows and failed batch statements, so this block keeps it+ // covered while `useBatchUpdates` describes the default batched path.+ groupStore = new BatchWritingGroupStore(groupRepository, clickhouseGroupRepository, {+ useBatchUpdates: false,+ })})afterEach(async () => {@@ -528,6 +534,221 @@ describe('BatchWritingGroupStore', () => {})})+ describe('useBatchCreates', () => {+ beforeEach(() => {+ // Updates pinned to the individual path so create-routing+ // assertions stay independent of the update flush mode.+ groupStore = new BatchWritingGroupStore(groupRepository, clickhouseGroupRepository, {+ useBatchCreates: true,+ useBatchUpdates: false,+ })+ })++ it('defers new groups to flush and inserts them in one statement, leaving updates on their own path', async () => {+ const timestamp = DateTime.now()+ // 'test' exists; the two new keys don't.+ jest.spyOn(groupRepository, 'fetchGroup').mockImplementation((_teamId, _groupTypeIndex, groupKey) =>+ Promise.resolve(groupKey === 'test' ? group : undefined)+ )+ const rowA = {+ ...group,+ group_type_index: 0 as GroupTypeIndex,+ group_key: 'new-a',+ group_properties: { a: '1' },+ created_at: timestamp,+ version: 1,+ inserted: true,+ }+ const rowB = {+ ...group,+ group_type_index: 1 as GroupTypeIndex,+ group_key: 'new-b',+ group_properties: { b: '2' },+ created_at: timestamp,+ version: 1,+ inserted: true,+ }+ jest.spyOn(groupRepository, 'insertGroupsBatch').mockResolvedValue([rowA, rowB])++ await groupStore.upsertGroup(teamId, projectId, 0, 'new-a', { a: '1' }, timestamp)+ await groupStore.upsertGroup(teamId, projectId, 1, 'new-b', { b: '2' }, timestamp)+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { u: '1' }, timestamp)++ // No inline insert during event processing.+ expect(groupRepository.insertGroup).not.toHaveBeenCalled()+ expect(groupRepository.insertGroupsBatch).not.toHaveBeenCalled()++ const results = await groupStore.flush()++ expect(groupRepository.insertGroup).not.toHaveBeenCalled()+ expect(groupRepository.insertGroupsBatch).toHaveBeenCalledTimes(1)+ expect(groupRepository.insertGroupsBatch).toHaveBeenCalledWith([+ { teamId, groupTypeIndex: 0, groupKey: 'new-a', groupProperties: { a: '1' }, createdAt: timestamp },+ { teamId, groupTypeIndex: 1, groupKey: 'new-b', groupProperties: { b: '2' }, createdAt: timestamp },+ ])+ // The existing group still goes through the regular update path.+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)+ expect(jest.mocked(groupRepository.updateGroupOptimistically).mock.calls[0][2]).toBe('test')++ // Each created group's ClickHouse message reflects its returned row.+ expect(results).toHaveLength(3)+ const messagesByKey = new Map(+ results.map((result) => [result.groupKey, parseJSON(result.messages[0].value.toString())])+ )+ expect(parseJSON(messagesByKey.get('new-a').group_properties)).toEqual({ a: '1' })+ expect(messagesByKey.get('new-a').version).toBe(1)+ expect(parseJSON(messagesByKey.get('new-b').group_properties)).toEqual({ b: '2' })+ expect(messagesByKey.get('new-b').version).toBe(1)++ // The cache converges on the authoritative inserted rows.+ expect(groupStore.getGroupCache().get(teamId, 0, 'new-a')?.version).toBe(1)+ expect(groupStore.getGroupCache().get(teamId, 1, 'new-b')?.version).toBe(1)+ })++ it('accumulates repeated events for a new group into a single creation', async () => {+ const timestamp = DateTime.now()+ jest.spyOn(groupRepository, 'fetchGroup').mockResolvedValue(undefined)+ jest.spyOn(groupRepository, 'insertGroupsBatch').mockResolvedValue([+ { ...group, group_key: 'new-key', group_properties: { a: '2', b: 'x' }, version: 1, inserted: true },+ ])++ await groupStore.upsertGroup(teamId, projectId, 1, 'new-key', { a: '1' }, timestamp)+ await groupStore.upsertGroup(teamId, projectId, 1, 'new-key', { a: '2', b: 'x' }, timestamp)++ await groupStore.flush()++ // One fetch, one batched insert carrying the merged view (later event wins).+ expect(groupRepository.fetchGroup).toHaveBeenCalledTimes(1)+ expect(groupRepository.insertGroupsBatch).toHaveBeenCalledTimes(1)+ expect(groupRepository.insertGroupsBatch).toHaveBeenCalledWith([+ {+ teamId,+ groupTypeIndex: 1,+ groupKey: 'new-key',+ groupProperties: { a: '2', b: 'x' },+ createdAt: timestamp,+ },+ ])+ })++ it('takes the merged row when a creation lost the cross-pod race, without extra round trips', async () => {+ const timestamp = DateTime.now()+ jest.spyOn(groupRepository, 'fetchGroup').mockResolvedValueOnce(undefined)+ // The row already existed: the statement merged our properties onto+ // the winner's row and flags it as not-inserted.+ jest.spyOn(groupRepository, 'insertGroupsBatch').mockResolvedValue([+ {+ ...group,+ group_key: 'new-key',+ group_properties: { test: 'test', a: '1' },+ version: 6,+ inserted: false,+ },+ ])++ await groupStore.upsertGroup(teamId, projectId, 1, 'new-key', { a: '1' }, timestamp)+ const results = await groupStore.flush()++ // No refetch, no CAS, no per-row insert — the merge already happened.+ expect(groupRepository.insertGroup).not.toHaveBeenCalled()+ expect(groupRepository.updateGroupOptimistically).not.toHaveBeenCalled()+ expect(groupRepository.fetchGroup).toHaveBeenCalledTimes(1)+ expect(results).toHaveLength(1)+ const message = parseJSON(results[0].messages[0].value.toString())+ expect(parseJSON(message.group_properties)).toEqual({ test: 'test', a: '1' })+ expect(message.version).toBe(6)+ expect(groupStore.getGroupCache().get(teamId, 1, 'new-key')?.version).toBe(6)+ })++ it('routes rows missing from the batch result through the individual update path', async () => {+ // Postgres returns one row per input, but a misbehaving repository+ // implementation (or a dropped guard) must not silently lose+ // creations — the residue converges through the standard CAS path.+ const timestamp = DateTime.now()+ jest.spyOn(groupRepository, 'fetchGroup')+ .mockResolvedValueOnce(undefined)+ .mockResolvedValue({ ...group, group_key: 'new-key', version: 5 })+ jest.spyOn(groupRepository, 'insertGroupsBatch').mockResolvedValue([])+ jest.spyOn(groupRepository, 'updateGroupOptimistically')+ .mockResolvedValueOnce(undefined) // version-0 CAS fails+ .mockResolvedValueOnce(6)++ await groupStore.upsertGroup(teamId, projectId, 1, 'new-key', { a: '1' }, timestamp)+ const results = await groupStore.flush()++ expect(groupRepository.insertGroup).not.toHaveBeenCalled()+ // Rebased onto the winner: version 5, our delta merged on top.+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(2)+ expect(groupRepository.updateGroupOptimistically).toHaveBeenLastCalledWith(+ teamId,+ 1,+ 'new-key',+ 5,+ { test: 'test', a: '1' },+ timestamp,+ {},+ {}+ )+ expect(results).toHaveLength(1)+ expect(parseJSON(results[0].messages[0].value.toString()).version).toBe(6)+ })++ it('falls back to individual inserts when the batch create statement fails', async () => {+ const timestamp = DateTime.now()+ jest.spyOn(groupRepository, 'fetchGroup').mockResolvedValue(undefined)+ jest.spyOn(groupRepository, 'insertGroupsBatch').mockRejectedValue(new Error('connection lost'))++ await groupStore.upsertGroup(teamId, projectId, 0, 'new-a', { a: '1' }, timestamp)+ await groupStore.upsertGroup(teamId, projectId, 1, 'new-b', { b: '2' }, timestamp)++ const results = await groupStore.flush()++ expect(groupRepository.insertGroup).toHaveBeenCalledTimes(2)+ expect(results).toHaveLength(2)+ const messagesByKey = new Map(+ results.map((result) => [result.groupKey, parseJSON(result.messages[0].value.toString())])+ )+ expect(parseJSON(messagesByKey.get('new-a').group_properties)).toEqual({ a: '1' })+ expect(parseJSON(messagesByKey.get('new-b').group_properties)).toEqual({ b: '2' })+ })++ it('claims pending creates synchronously at flush so a concurrent flush cannot double-insert', async () => {+ const timestamp = DateTime.now()+ jest.spyOn(groupRepository, 'fetchGroup').mockResolvedValue(undefined)+ let resolveInsert: (rows: GroupCreateResult[]) => void = () => {}+ jest.spyOn(groupRepository, 'insertGroupsBatch').mockImplementation(+ () => new Promise<GroupCreateResult[]>((resolve) => (resolveInsert = resolve))+ )+ jest.spyOn(groupRepository, 'updateGroupOptimistically').mockResolvedValue(2)++ await groupStore.upsertGroup(teamId, projectId, 1, 'new-key', { a: '1' }, timestamp)++ // Kick off flush WITHOUT awaiting: the claim must happen before any+ // DB I/O, so pendingCreate is already cleared here.+ const firstFlush = groupStore.flush()+ const entry = groupStore.getGroupCache().get(teamId, 1, 'new-key')+ expect(entry?.pendingCreate).toBe(false)+ expect(entry?.needsWrite).toBe(false)++ // Re-dirty the key while the insert is still in flight — a second+ // flush must capture it as a regular update, not a second insert.+ await groupStore.upsertGroup(teamId, projectId, 1, 'new-key', { b: '2' }, timestamp)+ const secondFlush = groupStore.flush()++ resolveInsert([+ { ...group, group_key: 'new-key', group_properties: { a: '1' }, version: 1, inserted: true },+ ])+ await Promise.all([firstFlush, secondFlush])++ expect(groupRepository.insertGroupsBatch).toHaveBeenCalledTimes(1)+ expect(groupRepository.insertGroup).not.toHaveBeenCalled()+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)+ // The insert's older row (version 1) must not regress the cache+ // entry the second flush already synced to its newer write.+ expect(groupStore.getGroupCache().get(teamId, 1, 'new-key')?.version).toBe(2)+ })+ })+describe('prefetchGroups', () => {it('serves subsequent upserts from the prefetched cache without single-row fetches', async () => {jest.spyOn(groupRepository, 'fetchGroupsByKeys').mockResolvedValue([diff --git a/nodejs/src/ingestion/common/groups/batch-writing-group-store.ts b/nodejs/src/ingestion/common/groups/batch-writing-group-store.tsindex 51f72af4180c..37b150f7f403 100644--- a/nodejs/src/ingestion/common/groups/batch-writing-group-store.ts+++ b/nodejs/src/ingestion/common/groups/batch-writing-group-store.ts@@ -6,7 +6,7 @@ import {GroupClickhouseMessage,} from '~/common/groups/repositories/clickhouse-group-repository'import { GroupRepositoryTransaction } from '~/common/groups/repositories/group-repository-transaction.interface'-import { GroupRepository } from '~/common/groups/repositories/group-repository.interface'+import { GroupCreateResult, GroupRepository } from '~/common/groups/repositories/group-repository.interface'import { logger } from '~/common/utils/logger'import { promiseRetry } from '~/common/utils/retries'import { RaceConditionError } from '~/common/utils/utils'@@ -18,6 +18,9 @@ import { logMissingRow, logVersionMismatch } from './group-logging'import { CacheMetrics, GroupFlushResult, GroupStore } from './group-store.interface'import { GroupUpdate, calculateUpdate, fromGroup } from './group-update'import {+ groupBatchCreateExecutedCounter,+ groupBatchCreateFallbackCounter,+ groupBatchCreateSizeHistogram,groupCacheOperationsCounter,groupCacheSizeHistogram,groupDatabaseOperationsPerBatchHistogram,@@ -310,6 +313,13 @@ export interface BatchWritingGroupStoreOptions {* optimistic version check.*/useBatchUpdates: boolean+ /**+ * When true, groups that don't exist yet are registered as virtual cache+ * entries and inserted at flush time in a single batched statement,+ * instead of an inline single-row insert per new group during event+ * processing.+ */+ useBatchCreates: boolean/*** Interval at which accumulated group operation metrics are emitted and* cleared. Set to 0 to disable the timer (used by tests; production@@ -322,7 +332,8 @@ const DEFAULT_OPTIONS: BatchWritingGroupStoreOptions = {maxConcurrentUpdates: 10,maxOptimisticUpdateRetries: 5,optimisticUpdateRetryInterval: 50,- useBatchUpdates: false,+ useBatchUpdates: true,+ useBatchCreates: false,metricEmissionIntervalMs: 30_000,}@@ -386,6 +397,7 @@ export class BatchWritingGroupStore implements GroupStore {// re-set `needsWrite=true` and be picked up by the next flush.// DO NOT introduce any `await` inside this block.const pendingWrites: PendingGroupWrite[] = []+ const pendingCreates: PendingGroupWrite[] = []for (const [key, update] of this.groupCache.entries()) {if (!update) {continue@@ -396,23 +408,39 @@ export class BatchWritingGroupStore implements GroupStore {update.needsWrite = falseconst propertiesToSet = update.properties_to_setupdate.properties_to_set = {}- pendingWrites.push({ update, propertiesToSet, cacheKey: key })+ if (update.pendingCreate) {+ // Clearing here means exactly one flush owns the INSERT: a+ // concurrent flush that captures later dirtying of this key+ // sees a regular update, which converges through the+ // individual-write path even if the insert hasn't landed yet.+ update.pendingCreate = false+ pendingCreates.push({ update, propertiesToSet, cacheKey: key })+ } else {+ pendingWrites.push({ update, propertiesToSet, cacheKey: key })+ }}// END synchronous linearization point.- if (pendingWrites.length === 0) {+ if (pendingWrites.length === 0 && pendingCreates.length === 0) {this.groupCache.processDeferredEvictions()return this.drainPendingFlushResults()}try {- const results = this.options.useBatchUpdates- ? await this.flushBatch(pendingWrites)- : await this.flushIndividual(pendingWrites)+ // A key is in exactly one of the two lists, so creates and+ // updates touch disjoint rows and can run concurrently.+ const [createResults, updateResults] = await Promise.all([+ pendingCreates.length > 0 ? this.flushCreates(pendingCreates) : [],+ pendingWrites.length === 0+ ? []+ : this.options.useBatchUpdates+ ? this.flushBatch(pendingWrites)+ : this.flushIndividual(pendingWrites),+ ])this.groupCache.processDeferredEvictions()// Drained after the writes so messages queued by fallback paths// during this flush ride this flush's side effects too.- return [...results, ...this.drainPendingFlushResults()]+ return [...createResults, ...updateResults, ...this.drainPendingFlushResults()]} catch (error) {logger.error('Failed to flush group updates', {error,@@ -465,45 +493,97 @@ export class BatchWritingGroupStore implements GroupStore {return await this.flushIndividual(pendingWrites)}- // Key by the full row identity — unlike the cache key, which omits- // group_type_index — so two group types sharing a group key can never- // sync each other's row.- const rowIdentity = (group: { team_id: TeamId; group_type_index: GroupTypeIndex; group_key: string }) =>- `${group.team_id}:${group.group_type_index}:${group.group_key}`const updatedByKey = new Map<string, Group>()for (const group of updatedGroups) {- updatedByKey.set(rowIdentity(group), group)+ updatedByKey.set(this.rowIdentity(group), group)}const results: GroupFlushResult[] = []const missingWrites: PendingGroupWrite[] = []for (const pendingWrite of pendingWrites) {- const row = updatedByKey.get(rowIdentity(pendingWrite.update))+ const row = updatedByKey.get(this.rowIdentity(pendingWrite.update))if (!row) {missingWrites.push(pendingWrite)continue}this.syncCacheEntryFromRow(pendingWrite.update, row)- results.push({- messages: [- this.clickhouseGroupRepository.buildUpsertMessage(- row.team_id,- row.group_type_index,- row.group_key,- row.group_properties,- row.created_at,- row.version- ),- ],- teamId: row.team_id,- groupTypeIndex: row.group_type_index,- groupKey: row.group_key,+ results.push(this.buildFlushResultFromRow(row))+ }++ if (missingWrites.length > 0) {+ results.push(...(await this.flushIndividual(missingWrites)))+ }++ return results+ }++ /**+ * Insert all pending group creations in one UNNEST statement. Rows that+ * lost a cross-pod race come back with `inserted: false` — the statement+ * already merged their properties onto the winning row server-side, so no+ * extra convergence round trip is needed. Rows absent from the result+ * (not expected from Postgres, but kept as a data-loss guard) converge+ * through the individual update path. A failure of the whole statement+ * falls back to per-row inserts (the pre-batching behavior), so no+ * captured creation is lost.+ */+ private async flushCreates(pendingCreates: PendingGroupWrite[]): Promise<GroupFlushResult[]> {+ this.incrementDatabaseOperation('insertGroupsBatch')+ groupBatchCreateSizeHistogram.observe(pendingCreates.length)++ let insertedGroups: GroupCreateResult[]+ try {+ insertedGroups = await this.groupRepository.insertGroupsBatch(+ pendingCreates.map(({ update, propertiesToSet }) => ({+ teamId: update.team_id,+ groupTypeIndex: update.group_type_index,+ groupKey: update.group_key,+ groupProperties: propertiesToSet,+ createdAt: update.created_at,+ }))+ )+ } catch (error) {+ groupBatchCreateFallbackCounter.inc({ reason: 'statement_failed' })+ logger.warn('⚠️', 'Batch group create failed, falling back to individual inserts', {+ count: pendingCreates.length,+ error,+ errorMessage: error instanceof Error ? error.message : String(error),})+ const limit = pLimit(this.options.maxConcurrentUpdates)+ const results = await Promise.all(+ pendingCreates.map((pendingCreate) => limit(() => this.createGroupIndividually(pendingCreate)))+ )+ return results.filter((result): result is GroupFlushResult => result !== null)+ }++ groupBatchCreateExecutedCounter.inc()++ const insertedByKey = new Map<string, GroupCreateResult>()+ for (const group of insertedGroups) {+ insertedByKey.set(this.rowIdentity(group), group)+ }++ const results: GroupFlushResult[] = []+ const missingWrites: PendingGroupWrite[] = []++ for (const pendingCreate of pendingCreates) {+ const row = insertedByKey.get(this.rowIdentity(pendingCreate.update))+ if (!row) {+ missingWrites.push(pendingCreate)+ continue+ }++ if (!row.inserted) {+ groupBatchCreateFallbackCounter.inc({ reason: 'lost_race' })+ }+ this.syncCacheEntryFromRow(pendingCreate.update, row)+ results.push(this.buildFlushResultFromRow(row))}if (missingWrites.length > 0) {+ groupBatchCreateFallbackCounter.inc({ reason: 'missing_row' }, missingWrites.length)results.push(...(await this.flushIndividual(missingWrites)))}@@ -511,13 +591,99 @@ export class BatchWritingGroupStore implements GroupStore {}/**- * Sync the cached entry with the authoritative row returned by the batch- * update, preserving any delta accumulated by concurrent batches since the- * flush captured this write.+ * Per-row insert fallback used when the batched create statement fails —+ * equivalent to the inline create that runs when batch creates are+ * disabled. A row that turns out to exist converges through the+ * individual update path instead.+ */+ private async createGroupIndividually(pendingCreate: PendingGroupWrite): Promise<GroupFlushResult | null> {+ const { update, propertiesToSet, cacheKey } = pendingCreate+ try {+ this.incrementDatabaseOperation('insertGroup')+ const insertedVersion = await this.groupRepository.insertGroup(+ update.team_id,+ update.group_type_index,+ update.group_key,+ propertiesToSet,+ update.created_at,+ {},+ {}+ )++ const insertedRow = {+ group_properties: propertiesToSet,+ created_at: update.created_at,+ version: insertedVersion,+ }+ this.syncCacheEntryFromRow(update, insertedRow)+ return {+ messages: [+ this.clickhouseGroupRepository.buildUpsertMessage(+ update.team_id,+ update.group_type_index,+ update.group_key,+ insertedRow.group_properties,+ insertedRow.created_at,+ insertedRow.version+ ),+ ],+ teamId: update.team_id,+ groupTypeIndex: update.group_type_index,+ groupKey: update.group_key,+ }+ } catch (error) {+ if (error instanceof RaceConditionError) {+ groupBatchCreateFallbackCounter.inc({ reason: 'lost_race' })+ return await this.processGroupUpdate(update, cacheKey)+ }+ throw error+ }+ }++ // Key by the full row identity — unlike the cache key, which omits+ // group_type_index — so two group types sharing a group key can never+ // sync each other's row.+ private rowIdentity(group: { team_id: TeamId; group_type_index: GroupTypeIndex; group_key: string }): string {+ return `${group.team_id}:${group.group_type_index}:${group.group_key}`+ }++ private buildFlushResultFromRow(row: Group): GroupFlushResult {+ return {+ messages: [+ this.clickhouseGroupRepository.buildUpsertMessage(+ row.team_id,+ row.group_type_index,+ row.group_key,+ row.group_properties,+ row.created_at,+ row.version+ ),+ ],+ teamId: row.team_id,+ groupTypeIndex: row.group_type_index,+ groupKey: row.group_key,+ }+ }++ /**+ * Sync the cached entry with the authoritative row returned by a write,+ * preserving any delta accumulated by concurrent batches since the flush+ * captured this write. A row older than the entry's synced state — a+ * concurrent flush's write landed while this statement was in flight —+ * is ignored: applying it would regress version and properties and+ * manufacture optimistic-update conflicts on the next flush. Cached+ * versions only ever come from authoritative reads and writes, so the+ * comparison is sound.*/- private syncCacheEntryFromRow(update: GroupUpdate, row: Group): void {+ private syncCacheEntryFromRow(+ update: GroupUpdate,+ row: Pick<Group, 'group_properties' | 'created_at' | 'version'>+ ): void {const cached = this.groupCache.get(update.team_id, update.group_type_index, update.group_key)const target = cached ?? update+ if (row.version < target.version) {+ return+ }target.group_properties = { ...row.group_properties, ...target.properties_to_set }target.created_at = DateTime.min(target.created_at, row.created_at)target.version = row.version@@ -636,6 +802,10 @@ export class BatchWritingGroupStore implements GroupStore {const group = await this.getGroup(teamId, groupTypeIndex, groupKey, false, groupCache)if (!group) {+ if (this.options.useBatchCreates) {+ this.queuePendingCreate(teamId, groupTypeIndex, groupKey, properties, timestamp, groupCache)+ return+ }await this.createGroup(teamId, groupTypeIndex, groupKey, properties, timestamp, batchId)return}@@ -653,10 +823,40 @@ export class BatchWritingGroupStore implements GroupStore {created_at: group.created_at,version: group.version,needsWrite: true,+ // Carried over so an accumulated-onto entry still routes to+ // the create list; false once a flush has claimed the insert.+ pendingCreate: group.pendingCreate,})}}+ /**+ * Register a group the cache says doesn't exist as a virtual entry; the+ * next flush inserts all pending creations in one batched statement.+ * Later events for the key accumulate onto the entry through the regular+ * update path, so per-lane ordering matches the inline-create flow.+ */+ private queuePendingCreate(+ teamId: TeamId,+ groupTypeIndex: GroupTypeIndex,+ groupKey: string,+ properties: Properties,+ timestamp: DateTime,+ groupCache: BatchBoundGroupCache+ ): void {+ groupCache.set(teamId, groupTypeIndex, groupKey, {+ team_id: teamId,+ group_type_index: groupTypeIndex,+ group_key: groupKey,+ group_properties: { ...properties },+ properties_to_set: { ...properties },+ created_at: DateTime.min(DateTime.now(), timestamp),+ version: 0,+ needsWrite: true,+ pendingCreate: true,+ })+ }+/*** Create a group that the cache says doesn't exist. Runs without a* wrapping transaction — the insert is a single ON CONFLICT DO NOTHINGdiff --git a/nodejs/src/ingestion/common/groups/group-update.ts b/nodejs/src/ingestion/common/groups/group-update.tsindex a4f8bbab2b58..0d155186a8c0 100644--- a/nodejs/src/ingestion/common/groups/group-update.ts+++ b/nodejs/src/ingestion/common/groups/group-update.ts@@ -18,6 +18,12 @@ export interface GroupUpdate {created_at: DateTimeversion: numberneedsWrite: boolean+ /**+ * The row doesn't exist in Postgres yet — the deferred-create path+ * installed this entry and the next flush inserts it in a batched+ * statement (version stays 0 until the insert returns the real row).+ */+ pendingCreate?: boolean}export interface PropertiesUpdate {diff --git a/nodejs/src/ingestion/common/groups/metrics.ts b/nodejs/src/ingestion/common/groups/metrics.tsindex d5e854f6ed42..586d43600fe4 100644--- a/nodejs/src/ingestion/common/groups/metrics.ts+++ b/nodejs/src/ingestion/common/groups/metrics.ts@@ -29,3 +29,20 @@ export const groupFetchPromisesCacheOperationsCounter = new Counter({help: 'Number of operations on the fetchPromises cache',labelNames: ['operation'],})++export const groupBatchCreateExecutedCounter = new Counter({+ name: 'group_batch_create_executed_total',+ help: 'Number of batched group create statements executed',+})++export const groupBatchCreateFallbackCounter = new Counter({+ name: 'group_batch_create_fallback_total',+ help: 'Group creations that did not land as plain batched inserts, by reason',+ labelNames: ['reason'],+})++export const groupBatchCreateSizeHistogram = new Histogram({+ name: 'group_batch_create_size',+ help: 'Number of group creations per batched insert statement',+ buckets: [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, Infinity],+})diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.tsindex 15f66a3e4180..c9046f1c896b 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -171,6 +171,10 @@ export type IngestionConsumerConfig = {// Group batch writing configGROUP_BATCH_WRITING_USE_BATCH_UPDATES: boolean+ // Defer creation of new groups to flush time and insert them in a single+ // batched statement, instead of an inline single-row insert per new group+ // during event processing. When off, behavior is unchanged.+ GROUP_BATCH_WRITING_USE_BATCH_CREATES: booleanGROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES: numberGROUP_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES: numberGROUP_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS: number@@ -308,7 +312,8 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',// Group batch writing config- GROUP_BATCH_WRITING_USE_BATCH_UPDATES: false,+ GROUP_BATCH_WRITING_USE_BATCH_UPDATES: true,+ GROUP_BATCH_WRITING_USE_BATCH_CREATES: false,GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES: 10,GROUP_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES: 5,GROUP_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS: 50,diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex b6726f8fe598..c5aaf81c49d7 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -226,6 +226,7 @@ export class IngestionConsumer {this.groupStore = new BatchWritingGroupStore(this.deps.groupRepository, this.deps.clickhouseGroupRepository, {useBatchUpdates: this.config.GROUP_BATCH_WRITING_USE_BATCH_UPDATES,+ useBatchCreates: this.config.GROUP_BATCH_WRITING_USE_BATCH_CREATES,maxConcurrentUpdates: this.config.GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES,maxOptimisticUpdateRetries: this.config.GROUP_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES,optimisticUpdateRetryInterval: this.config.GROUP_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex a6a7c700eff9..7fceb4237d9b 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -364,6 +364,7 @@ export class IngestionApiServer implements NodeServer {this.groupStore = new BatchWritingGroupStore(groupRepository, clickhouseGroupRepository, {useBatchUpdates: this.config.GROUP_BATCH_WRITING_USE_BATCH_UPDATES,+ useBatchCreates: this.config.GROUP_BATCH_WRITING_USE_BATCH_CREATES,maxConcurrentUpdates: this.config.GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES,maxOptimisticUpdateRetries: this.config.GROUP_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES,optimisticUpdateRetryInterval: this.config.GROUP_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,diff --git a/nodejs/tests/ingestion/ingestion-e2e.test.ts b/nodejs/tests/ingestion/ingestion-e2e.test.tsindex 6edc1c2de267..9e2c76a4f32d 100644--- a/nodejs/tests/ingestion/ingestion-e2e.test.ts+++ b/nodejs/tests/ingestion/ingestion-e2e.test.ts@@ -21,7 +21,7 @@ import {import { createTestIngestionOutputs, createTestMonitoringOutputs } from '~/tests/helpers/ingestion-outputs'import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'import { createUserTeamAndOrganization, fetchPostgresPersons, resetTestDatabase } from '~/tests/helpers/sql'-import { InternalPerson } from '~/types'+import { GroupTypeIndex, InternalPerson } from '~/types'// Mock the limiter so it always returns truejest.mock('~/common/utils/token-bucket', () => {@@ -35,10 +35,26 @@ jest.mock('~/common/utils/token-bucket', () => {jest.mock('~/common/utils/logger')+// Two diagonal arms rather than a full cross: one with every optimization off+// and one with them all on, keeping CI cost flat while both modes stay fully+// covered. Batched group updates default to on, so the off arm pins them off+// to keep the individual CAS flush path (still the fallback) e2e-covered.describe.each([- { PERSONS_PREFETCH_ENABLED: true, PERSON_MERGE_FOLD_ENABLED: false },- { PERSONS_PREFETCH_ENABLED: true, PERSON_MERGE_FOLD_ENABLED: true },-])('Event Pipeline E2E tests (fold=$PERSON_MERGE_FOLD_ENABLED)', (pipelineConfig) => {+ {+ PERSONS_PREFETCH_ENABLED: true,+ PERSON_MERGE_FOLD_ENABLED: false,+ GROUPS_PREFETCH_ENABLED: false,+ GROUP_BATCH_WRITING_USE_BATCH_CREATES: false,+ GROUP_BATCH_WRITING_USE_BATCH_UPDATES: false,+ },+ {+ PERSONS_PREFETCH_ENABLED: true,+ PERSON_MERGE_FOLD_ENABLED: true,+ GROUPS_PREFETCH_ENABLED: true,+ GROUP_BATCH_WRITING_USE_BATCH_CREATES: true,+ GROUP_BATCH_WRITING_USE_BATCH_UPDATES: true,+ },+])('Event Pipeline E2E tests (fold+groupBatchCreates=$PERSON_MERGE_FOLD_ENABLED)', (pipelineConfig) => {const testWithTeamIngester = createTestWithTeamIngester(pipelineConfig, (infra, kafkaProducer) => {const outputs = createTestIngestionOutputs(kafkaProducer)const ingester = new IngestionConsumer(infra.config, {@@ -63,11 +79,18 @@ describe.each([}),})jest.spyOn(infra.groupRepository, 'fetchGroup')+ jest.spyOn(infra.groupRepository, 'fetchGroupsByKeys')jest.spyOn(infra.groupRepository, 'insertGroup')+ jest.spyOn(infra.groupRepository, 'insertGroupsBatch')jest.spyOn(infra.groupRepository, 'updateGroup')+ jest.spyOn(infra.groupRepository, 'updateGroupsBatch')jest.spyOn(infra.groupRepository, 'updateGroupOptimistically')return ingester})+ // Group creations land differently per arm: inline single-row inserts+ // (version 1 + a follow-up update) versus a single deferred batched insert+ // carrying the accumulated properties (version 1, no update needed).+ const groupBatchCreates = pipelineConfig.GROUP_BATCH_WRITING_USE_BATCH_CREATESlet clickhouse: ClickhousebeforeAll(async () => {console.log('Creating Clickhouse client')@@ -166,9 +189,15 @@ describe.each([expect(events[1].properties.$group_set).toEqual({ prop: 'value' })})- // Should have fetched the group 4 times:- // 1 for each event and 2 in test check- expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(4)+ // 1 single-row fetch per event and 2 in the test checks — except+ // with groups prefetch on, where the second batch's fetch happens+ // through the chunk-level batched query instead.+ if (groupBatchCreates) {+ expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(3)+ expect(infra.groupRepository.fetchGroupsByKeys).toHaveBeenCalledTimes(1)+ } else {+ expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(4)+ }})@@ -200,9 +229,17 @@ describe.each([})expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(1)- expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(1)expect(infra.groupRepository.updateGroup).toHaveBeenCalledTimes(0)- expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)+ if (groupBatchCreates) {+ // The whole storm folds into one batched insert carrying all+ // accumulated properties — no follow-up update needed.+ expect(infra.groupRepository.insertGroupsBatch).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(0)+ expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(0)+ } else {+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)+ }})@@ -247,9 +284,15 @@ describe.each([})expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(1)- expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(1)expect(infra.groupRepository.updateGroup).toHaveBeenCalledTimes(0)- expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)+ if (groupBatchCreates) {+ expect(infra.groupRepository.insertGroupsBatch).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(0)+ expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(0)+ } else {+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)+ }await waitForExpect(async () => {const group = await infra.groupRepository.fetchGroup(team.id, 0, groupKey)@@ -257,10 +300,13 @@ describe.each([expect.objectContaining({team_id: team.id,group_type_index: 0,+ // In-batch event order still decides conflicting keys+ // (k2 comes from the last event) in both modes.group_properties: { k1: 'v1', k2: 'v3', k3: 'v2', k4: 'v3' },group_key: groupKey,- // Just one write after the creation of the group- version: 2,+ // One write after the creation — or a single batched+ // create carrying everything.+ version: groupBatchCreates ? 1 : 2,}))})@@ -317,6 +363,14 @@ describe.each([await waitForKafkaMessages(kafkaProducer)+ // Creations from different lanes aggregate into one statement.+ if (groupBatchCreates) {+ expect(infra.groupRepository.insertGroupsBatch).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(0)+ } else {+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(n)+ }+await waitForExpect(async () => {const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(n * 2)@@ -330,7 +384,7 @@ describe.each([team_id: team.id,group_type_index: 0,group_properties: { foo: 'bar', update: 'new' },- version: 2,+ version: groupBatchCreates ? 1 : 2,}))})@@ -339,54 +393,220 @@ describe.each([)testWithTeamIngester(- 'can handle multiple $groupidentify for different distinct ids',+ 'batches creation of many new groups from a single distinct id',{},async ({ ingester, infra, team, kafkaProducer, token }) => {+ // The production shape of a create storm: one distinct_id (one+ // sequential lane) referencing many groups that don't exist yet.const n = 50- const distinctIds = []- for (let i = 0; i < n; i++) {- distinctIds.push(new UUIDT().toString())- }-+ const distinctId = new UUIDT().toString()const events = []- for (const distinctId of distinctIds) {- events.push(- new EventBuilder(team, distinctId)- .withEvent('$groupidentify')- .withGroupProperties('organization', distinctId, { foo: 'bar' })- .build()- )+ for (let i = 0; i < n; i++) {events.push(new EventBuilder(team, distinctId).withEvent('$groupidentify')- .withGroupProperties('organization', distinctId, { update: 'new' })+ .withGroupProperties('organization', `group-${i}`, { idx: i }).build())}- // handle 100 events in one batchawait ingester.handleKafkaBatch(createKafkaMessages(events, token))await waitForKafkaMessages(kafkaProducer)+ // Call-count assertions come before the Postgres checks below,+ // which go through the same spied repository.+ if (groupBatchCreates) {+ expect(infra.groupRepository.insertGroupsBatch).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(0)+ } else {+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(n)+ }+ expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(0)++ for (let i = 0; i < n; i++) {+ const group = await infra.groupRepository.fetchGroup(team.id, 0, `group-${i}`)+ expect(group).toEqual(+ expect.objectContaining({+ team_id: team.id,+ group_properties: { idx: i },+ version: 1,+ })+ )+ }+await waitForExpect(async () => {const events = await fetchEvents(clickhouse, team.id)- expect(events.length).toEqual(n * 2)+ expect(events.length).toEqual(n)})- for (const distinctId of distinctIds) {- await waitForExpect(async () => {- const group = await infra.groupRepository.fetchGroup(team.id, 0, distinctId)- expect(group).toEqual(- expect.objectContaining({- team_id: team.id,- group_type_index: 0,- group_properties: { foo: 'bar', update: 'new' },- version: 2,- })- )- })+ // Every creation's ClickHouse message made it to the groups table.+ await waitForExpect(async () => {+ const chGroups = (await clickhouse.fetchClickhouseGroups()).filter(+ (chGroup) => Number(chGroup.team_id) === team.id+ )+ expect(chGroups).toHaveLength(n)+ })+ }+ )++ testWithTeamIngester(+ 'keeps write amplification bounded for a mixed batch of group creates and updates',+ {},+ async ({ ingester, infra, team, kafkaProducer, token }) => {+ // One batch mixing creates and updates across several groups, two+ // group types sharing a group key, and three lanes. Writes must+ // scale with the number of groups touched, never with the number+ // of events, and every group must converge to its merged state.+ const setupId = new UUIDT().toString()+ await ingester.handleKafkaBatch(+ createKafkaMessages(+ [+ new EventBuilder(team, setupId)+ .withEvent('$groupidentify')+ .withGroupProperties('organization', 'acme', { plan: 'free' })+ .build(),+ new EventBuilder(team, setupId)+ .withEvent('$groupidentify')+ .withGroupProperties('organization', 'globex', { region: 'eu' })+ .build(),+ new EventBuilder(team, setupId)+ .withEvent('$groupidentify')+ .withGroupProperties('project', 'acme', { tier: 'a' })+ .build(),+ ],+ token+ )+ )+ await waitForKafkaMessages(kafkaProducer)++ // Measure only the mixed batch, not the setup writes.+ jest.mocked(infra.groupRepository.fetchGroup).mockClear()+ jest.mocked(infra.groupRepository.fetchGroupsByKeys).mockClear()+ jest.mocked(infra.groupRepository.insertGroup).mockClear()+ jest.mocked(infra.groupRepository.insertGroupsBatch).mockClear()+ jest.mocked(infra.groupRepository.updateGroup).mockClear()+ jest.mocked(infra.groupRepository.updateGroupsBatch).mockClear()+ jest.mocked(infra.groupRepository.updateGroupOptimistically).mockClear()++ // Same-group traffic stays within one lane (cross-lane writes to+ // one group have no ordering guarantee); lanes touch disjoint+ // groups so the final state is deterministic.+ const d1 = new UUIDT().toString()+ const d2 = new UUIDT().toString()+ const d3 = new UUIDT().toString()+ const events = [+ // Lane d1: three updates to one existing group → one write.+ new EventBuilder(team, d1)+ .withEvent('$groupidentify')+ .withGroupProperties('organization', 'acme', { plan: 'scale' })+ .build(),+ new EventBuilder(team, d1)+ .withEvent('$groupidentify')+ .withGroupProperties('organization', 'acme', { seats: 5 })+ .build(),+ new EventBuilder(team, d1)+ .withEvent('$groupidentify')+ .withGroupProperties('organization', 'acme', { plan: 'enterprise' })+ .build(),+ // Lane d2: a new group written twice, and an update to the+ // OTHER type's group behind the same group key.+ new EventBuilder(team, d2)+ .withEvent('$groupidentify')+ .withGroupProperties('organization', 'new-1', { a: '1' })+ .build(),+ new EventBuilder(team, d2)+ .withEvent('$groupidentify')+ .withGroupProperties('organization', 'new-1', { b: '2' })+ .build(),+ new EventBuilder(team, d2)+ .withEvent('$groupidentify')+ .withGroupProperties('project', 'acme', { tier: 'b' })+ .build(),+ // Lane d3: a new group in the second type sharing the first+ // type's new key, and one more update.+ new EventBuilder(team, d3)+ .withEvent('$groupidentify')+ .withGroupProperties('project', 'new-1', { c: '3' })+ .build(),+ new EventBuilder(team, d3)+ .withEvent('$groupidentify')+ .withGroupProperties('organization', 'globex', { mrr: 100 })+ .build(),+ ]++ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)++ // 8 events over 5 groups. Call-count assertions come before the+ // Postgres checks below, which go through the spied repository.+ expect(infra.groupRepository.updateGroup).toHaveBeenCalledTimes(0)+ if (groupBatchCreates) {+ // Fully batched: one read, one insert for both new groups,+ // one update statement for all three dirty groups.+ expect(infra.groupRepository.fetchGroupsByKeys).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(0)+ expect(infra.groupRepository.insertGroupsBatch).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(0)+ expect(infra.groupRepository.updateGroupsBatch).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(0)+ } else {+ // One fetch per group, one insert per new group, one CAS per+ // dirty group (the twice-written new group needs a follow-up).+ expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(5)+ expect(infra.groupRepository.insertGroupsBatch).toHaveBeenCalledTimes(0)+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(2)+ expect(infra.groupRepository.updateGroupsBatch).toHaveBeenCalledTimes(0)+ expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(4)}++ const expectedGroups = [+ {+ groupTypeIndex: 0,+ groupKey: 'acme',+ properties: { plan: 'enterprise', seats: 5 },+ version: 2,+ },+ { groupTypeIndex: 0, groupKey: 'globex', properties: { region: 'eu', mrr: 100 }, version: 2 },+ {+ groupTypeIndex: 0,+ groupKey: 'new-1',+ properties: { a: '1', b: '2' },+ version: groupBatchCreates ? 1 : 2,+ },+ { groupTypeIndex: 1, groupKey: 'acme', properties: { tier: 'b' }, version: 2 },+ { groupTypeIndex: 1, groupKey: 'new-1', properties: { c: '3' }, version: 1 },+ ]+ for (const expected of expectedGroups) {+ const group = await infra.groupRepository.fetchGroup(+ team.id,+ expected.groupTypeIndex as GroupTypeIndex,+ expected.groupKey+ )+ expect(group).toEqual(+ expect.objectContaining({+ team_id: team.id,+ group_type_index: expected.groupTypeIndex,+ group_key: expected.groupKey,+ group_properties: expected.properties,+ version: expected.version,+ })+ )+ }++ await waitForExpect(async () => {+ const chEvents = await fetchEvents(clickhouse, team.id)+ expect(chEvents.length).toEqual(11)+ })++ // All five groups (the shared key counts once per type) reached+ // the ClickHouse groups table.+ await waitForExpect(async () => {+ const chGroups = (await clickhouse.fetchClickhouseGroups()).filter(+ (chGroup) => Number(chGroup.team_id) === team.id+ )+ expect(chGroups).toHaveLength(5)+ })})