Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ingestion): remove personless-table write machinery (#80861)

José Sequeira4d63ea884f99
diff --git a/nodejs/src/common/personhog/personhog-person-repository.test.ts b/nodejs/src/common/personhog/personhog-person-repository.test.ts
index 7e03c88a1ba7..0b7aa8323051 100644
--- a/nodejs/src/common/personhog/personhog-person-repository.test.ts
+++ b/nodejs/src/common/personhog/personhog-person-repository.test.ts
@@ -84,9 +84,6 @@ function createMockPostgres(): jest.Mocked<PersonRepository> {
updatePersonsBatch: jest.fn(),
deletePerson: jest.fn(),
addDistinctId: jest.fn(),
- addPersonlessDistinctId: jest.fn(),
- addPersonlessDistinctIdForMerge: jest.fn(),
- addPersonlessDistinctIdsBatch: jest.fn(),
personPropertiesSize: jest.fn(),
updateCohortsAndFeatureFlagsForMerge: jest.fn(),
inTransaction: jest.fn(),
diff --git a/nodejs/src/common/personhog/personhog-person-repository.ts b/nodejs/src/common/personhog/personhog-person-repository.ts
index 9e034becc4cd..89721db6b04d 100644
--- a/nodejs/src/common/personhog/personhog-person-repository.ts
+++ b/nodejs/src/common/personhog/personhog-person-repository.ts
@@ -220,18 +220,6 @@ export class PersonHogPersonRepository implements PersonRepository {
return this.postgres.addDistinctId(person, distinctId, version)
}
- addPersonlessDistinctId(teamId: Team['id'], distinctId: string): Promise<boolean> {
- return this.postgres.addPersonlessDistinctId(teamId, distinctId)
- }
-
- addPersonlessDistinctIdForMerge(teamId: Team['id'], distinctId: string): Promise<boolean> {
- return this.postgres.addPersonlessDistinctIdForMerge(teamId, distinctId)
- }
-
- addPersonlessDistinctIdsBatch(entries: { teamId: number; distinctId: string }[]): Promise<Map<string, boolean>> {
- return this.postgres.addPersonlessDistinctIdsBatch(entries)
- }
-
personPropertiesSize(personId: string, teamId: number): Promise<number> {
return this.postgres.personPropertiesSize(personId, teamId)
}
diff --git a/nodejs/src/common/persons/repositories/person-repository-transaction.ts b/nodejs/src/common/persons/repositories/person-repository-transaction.ts
index b47d1bdde7f9..cf34805ab81f 100644
--- a/nodejs/src/common/persons/repositories/person-repository-transaction.ts
+++ b/nodejs/src/common/persons/repositories/person-repository-transaction.ts
@@ -42,8 +42,6 @@ export interface PersonRepositoryTransaction {
fetchPersonDistinctIds(person: InternalPerson, limit?: number): Promise<string[]>
- addPersonlessDistinctIdForMerge(teamId: Team['id'], distinctId: string): Promise<boolean>
-
updateCohortsAndFeatureFlagsForMerge(
teamId: Team['id'],
sourcePersonID: InternalPerson['id'],
diff --git a/nodejs/src/common/persons/repositories/person-repository.ts b/nodejs/src/common/persons/repositories/person-repository.ts
index f27022c6602b..a5340ca62779 100644
--- a/nodejs/src/common/persons/repositories/person-repository.ts
+++ b/nodejs/src/common/persons/repositories/person-repository.ts
@@ -148,10 +148,6 @@ export interface PersonRepository {
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>
- addPersonlessDistinctId(teamId: Team['id'], distinctId: string): Promise<boolean>
- addPersonlessDistinctIdForMerge(teamId: Team['id'], distinctId: string): Promise<boolean>
- addPersonlessDistinctIdsBatch(entries: { teamId: number; distinctId: string }[]): Promise<Map<string, boolean>>
-
personPropertiesSize(personId: string, teamId: number): Promise<number>
updateCohortsAndFeatureFlagsForMerge(
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts b/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts
index 7741fceb5dc5..e51537cf0109 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts
@@ -88,10 +88,6 @@ export class PostgresPersonRepositoryTransaction implements PersonRepositoryTran
return await this.repository.fetchPersonDistinctIds(person, limit, this.transaction)
}
- async addPersonlessDistinctIdForMerge(teamId: Team['id'], distinctId: string): Promise<boolean> {
- return await this.repository.addPersonlessDistinctIdForMerge(teamId, distinctId, this.transaction)
- }
-
async updateCohortsAndFeatureFlagsForMerge(
teamID: Team['id'],
sourcePersonID: InternalPerson['id'],
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
index 0a64855a683c..3b0c57868b5d 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
@@ -1089,254 +1089,6 @@ describe('PostgresPersonRepository', () => {
})
})
- describe('addPersonlessDistinctId', () => {
- it('should insert personless distinct ID successfully', async () => {
- const team = await getFirstTeam(hub.postgres)
- const distinctId = 'test-distinct-new'
-
- const result = await repository.addPersonlessDistinctId(team.id, distinctId)
-
- expect(result).toBe(false) // is_merged should be false for new insert
-
- // Verify the record was actually inserted
- const selectResult = await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `SELECT is_merged FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2`,
- [team.id, distinctId],
- 'verifyInsert'
- )
-
- expect(selectResult.rows).toHaveLength(1)
- expect(selectResult.rows[0].is_merged).toBe(false)
- })
-
- it('should return existing is_merged value when distinct ID already exists', async () => {
- const team = await getFirstTeam(hub.postgres)
- const distinctId = 'test-distinct-existing'
-
- // First insert
- const firstResult = await repository.addPersonlessDistinctId(team.id, distinctId)
- expect(firstResult).toBe(false) // is_merged should be false for new insert
-
- // Second insert with same distinct ID - should return existing value
- const secondResult = await repository.addPersonlessDistinctId(team.id, distinctId)
- expect(secondResult).toBe(false) // should still be false since we didn't merge it
-
- // Verify only one record exists
- const selectResult = await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `SELECT COUNT(*) as count FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2`,
- [team.id, distinctId],
- 'verifyCount'
- )
-
- expect(selectResult.rows[0].count).toBe('1')
- })
-
- it('should handle different team IDs correctly', async () => {
- const team1 = await getFirstTeam(hub.postgres)
- const team2Id = await createTeam(hub.postgres, team1.organization_id)
- const distinctId = 'shared-distinct-id'
-
- // Insert for team 1
- const result1 = await repository.addPersonlessDistinctId(team1.id, distinctId)
- expect(result1).toBe(false)
-
- // Insert for team 2 (should work since it's a different team)
- const result2 = await repository.addPersonlessDistinctId(team2Id, distinctId)
- expect(result2).toBe(false)
-
- // Verify both records exist
- const selectResult1 = await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `SELECT is_merged FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2`,
- [team1.id, distinctId],
- 'verifyTeam1'
- )
-
- const selectResult2 = await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `SELECT is_merged FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2`,
- [team2Id, distinctId],
- 'verifyTeam2'
- )
-
- expect(selectResult1.rows).toHaveLength(1)
- expect(selectResult2.rows).toHaveLength(1)
- expect(selectResult1.rows[0].is_merged).toBe(false)
- expect(selectResult2.rows[0].is_merged).toBe(false)
- })
- })
-
- describe('addPersonlessDistinctIdForMerge', () => {
- it('should insert personless distinct ID for merge successfully', async () => {
- const team = await getFirstTeam(hub.postgres)
- const distinctId = 'test-distinct-merge-new'
-
- const result = await repository.addPersonlessDistinctIdForMerge(team.id, distinctId)
-
- expect(result).toBe(true) // inserted should be true for new insert
-
- // Verify the record was actually inserted with is_merged = true
- const selectResult = await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `SELECT is_merged FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2`,
- [team.id, distinctId],
- 'verifyMergeInsert'
- )
-
- expect(selectResult.rows).toHaveLength(1)
- expect(selectResult.rows[0].is_merged).toBe(true)
- })
-
- it('should update existing record to merged when distinct ID already exists', async () => {
- const team = await getFirstTeam(hub.postgres)
- const distinctId = 'test-distinct-merge-existing'
-
- // First insert as regular personless distinct ID
- const firstResult = await repository.addPersonlessDistinctId(team.id, distinctId)
- expect(firstResult).toBe(false) // is_merged should be false initially
-
- // Verify initial state
- let selectResult = await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `SELECT is_merged FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2`,
- [team.id, distinctId],
- 'verifyInitialState'
- )
- expect(selectResult.rows[0].is_merged).toBe(false)
-
- // Now mark it for merge
- const mergeResult = await repository.addPersonlessDistinctIdForMerge(team.id, distinctId)
- expect(mergeResult).toBe(false) // inserted should be false since record already existed
-
- // Verify it was updated to merged
- selectResult = await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `SELECT is_merged FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2`,
- [team.id, distinctId],
- 'verifyMergeUpdate'
- )
- expect(selectResult.rows[0].is_merged).toBe(true)
- })
-
- it('should handle transaction parameter correctly', async () => {
- const team = await getFirstTeam(hub.postgres)
- const distinctId = 'test-distinct-merge-transaction'
-
- // Use a transaction
- await postgres.transaction(PostgresUse.PERSONS_WRITE, 'test-transaction', async (tx) => {
- const result = await repository.addPersonlessDistinctIdForMerge(team.id, distinctId, tx)
- expect(result).toBe(true)
-
- // Verify within transaction
- const selectResult = await postgres.query(
- tx,
- `SELECT is_merged FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2`,
- [team.id, distinctId],
- 'verifyInTransaction'
- )
- expect(selectResult.rows).toHaveLength(1)
- expect(selectResult.rows[0].is_merged).toBe(true)
- })
-
- // Verify after transaction
- const selectResult = await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `SELECT is_merged FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2`,
- [team.id, distinctId],
- 'verifyAfterTransaction'
- )
- expect(selectResult.rows).toHaveLength(1)
- expect(selectResult.rows[0].is_merged).toBe(true)
- })
- })
-
- describe('addPersonlessDistinctIdsBatch', () => {
- it('should insert multiple personless distinct IDs in batch', async () => {
- const team = await getFirstTeam(hub.postgres)
- const entries = [
- { teamId: team.id, distinctId: 'batch-distinct-1' },
- { teamId: team.id, distinctId: 'batch-distinct-2' },
- { teamId: team.id, distinctId: 'batch-distinct-3' },
- ]
-
- const results = await repository.addPersonlessDistinctIdsBatch(entries)
-
- // All should be not merged (new inserts)
- expect(results.size).toBe(3)
- expect(results.get(`${team.id}|batch-distinct-1`)).toBe(false)
- expect(results.get(`${team.id}|batch-distinct-2`)).toBe(false)
- expect(results.get(`${team.id}|batch-distinct-3`)).toBe(false)
-
- // Verify records were inserted
- const selectResult = await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `SELECT distinct_id, is_merged FROM posthog_personlessdistinctid WHERE team_id = $1 ORDER BY distinct_id`,
- [team.id],
- 'verifyBatchInsert'
- )
- expect(selectResult.rows).toHaveLength(3)
- })
-
- it('should handle duplicate distinct IDs in batch (deduplicates)', async () => {
- const team = await getFirstTeam(hub.postgres)
- const entries = [
- { teamId: team.id, distinctId: 'dup-distinct' },
- { teamId: team.id, distinctId: 'dup-distinct' },
- { teamId: team.id, distinctId: 'other-distinct' },
- ]
-
- const results = await repository.addPersonlessDistinctIdsBatch(entries)
-
- // Should have 2 unique entries
- expect(results.size).toBe(2)
- expect(results.get(`${team.id}|dup-distinct`)).toBe(false)
- expect(results.get(`${team.id}|other-distinct`)).toBe(false)
- })
-
- it('should return is_merged=true for already merged distinct IDs', async () => {
- const team = await getFirstTeam(hub.postgres)
- const mergedDistinctId = 'already-merged-distinct'
-
- // First, insert and mark as merged
- await repository.addPersonlessDistinctIdForMerge(team.id, mergedDistinctId)
-
- // Now try to batch insert including the merged one
- const entries = [
- { teamId: team.id, distinctId: mergedDistinctId },
- { teamId: team.id, distinctId: 'new-distinct' },
- ]
-
- const results = await repository.addPersonlessDistinctIdsBatch(entries)
-
- expect(results.size).toBe(2)
- expect(results.get(`${team.id}|${mergedDistinctId}`)).toBe(true) // Already merged
- expect(results.get(`${team.id}|new-distinct`)).toBe(false) // New insert
- })
-
- it('should handle empty batch', async () => {
- const results = await repository.addPersonlessDistinctIdsBatch([])
- expect(results.size).toBe(0)
- })
-
- it('should handle multiple teams in same batch', async () => {
- const team1 = await getFirstTeam(hub.postgres)
- const team2Id = await createTeam(hub.postgres, team1.organization_id)
-
- const entries = [
- { teamId: team1.id, distinctId: 'shared-distinct' },
- { teamId: team2Id, distinctId: 'shared-distinct' },
- ]
-
- const results = await repository.addPersonlessDistinctIdsBatch(entries)
-
- expect(results.size).toBe(2)
- expect(results.get(`${team1.id}|shared-distinct`)).toBe(false)
- expect(results.get(`${team2Id}|shared-distinct`)).toBe(false)
- })
- })
-
describe('personPropertiesSize', () => {
it('should return properties size for existing person', async () => {
const team = await getFirstTeam(hub.postgres)
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
index 6f0f2669a14b..ec94af445b96 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
@@ -1021,91 +1021,6 @@ export class PostgresPersonRepository
return rows.map((row) => row.distinct_id)
}
- async addPersonlessDistinctId(teamId: number, distinctId: string, tx?: TransactionClient): Promise<boolean> {
- // Use ON CONFLICT DO UPDATE with a no-op to always get the RETURNING clause.
- // This eliminates the need for a fallback SELECT query on conflict (~10k queries/min saved).
- // The no-op update on is_merged (not indexed) results in a HOT update, which is very cheap:
- // - No index maintenance required
- // - Creates a dead tuple that gets cleaned up by autovacuum
- const result = await this.postgres.query(
- tx ?? PostgresUse.PERSONS_WRITE,
- `
- INSERT INTO posthog_personlessdistinctid (team_id, distinct_id, is_merged, created_at)
- VALUES ($1, $2, false, now())
- ON CONFLICT (team_id, distinct_id) DO UPDATE
- SET is_merged = posthog_personlessdistinctid.is_merged
- RETURNING is_merged
- `,
- [teamId, distinctId],
- 'addPersonlessDistinctId'
- )
-
- return result.rows[0]['is_merged']
- }
-
- async addPersonlessDistinctIdForMerge(
- teamId: number,
- distinctId: string,
- tx?: TransactionClient
- ): Promise<boolean> {
- const result = await this.postgres.query(
- tx ?? PostgresUse.PERSONS_WRITE,
- `
- INSERT INTO posthog_personlessdistinctid (team_id, distinct_id, is_merged, created_at)
- VALUES ($1, $2, true, now())
- ON CONFLICT (team_id, distinct_id) DO UPDATE
- SET is_merged = true
- RETURNING (xmax = 0) AS inserted
- `,
- [teamId, distinctId],
- 'addPersonlessDistinctIdForMerge'
- )
-
- return result.rows[0].inserted
- }
-
- async addPersonlessDistinctIdsBatch(
- entries: { teamId: number; distinctId: string }[]
- ): Promise<Map<string, boolean>> {
- if (entries.length === 0) {
- return new Map()
- }
-
- // Deduplicate entries to avoid PostgreSQL "ON CONFLICT DO UPDATE command cannot affect row a second time" error
- const seen = new Set<string>()
- const uniqueEntries: { teamId: number; distinctId: string }[] = []
- for (const entry of entries) {
- const key = `${entry.teamId}|${entry.distinctId}`
- if (!seen.has(key)) {
- seen.add(key)
- uniqueEntries.push(entry)
- }
- }
-
- const teamIds = uniqueEntries.map((e) => e.teamId)
- const distinctIds = uniqueEntries.map((e) => e.distinctId)
-
- const result = await this.postgres.query(
- PostgresUse.PERSONS_WRITE,
- `
- INSERT INTO posthog_personlessdistinctid (team_id, distinct_id, is_merged, created_at)
- SELECT team_id, distinct_id, false, now()
- FROM UNNEST($1::integer[], $2::text[]) AS batch(team_id, distinct_id)
- ON CONFLICT (team_id, distinct_id) DO UPDATE
- SET is_merged = posthog_personlessdistinctid.is_merged
- RETURNING team_id, distinct_id, is_merged
- `,
- [teamIds, distinctIds],
- 'addPersonlessDistinctIdsBatch'
- )
-
- const resultMap = new Map<string, boolean>()
- for (const row of result.rows) {
- resultMap.set(`${row.team_id}|${row.distinct_id}`, row.is_merged)
- }
- return resultMap
- }
-
async personPropertiesSize(personId: string, teamId: number): Promise<number> {
const queryString = `
SELECT COALESCE(pg_column_size(properties)::bigint, 0::bigint) AS total_props_bytes
diff --git a/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts b/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts
index 180e98996d6e..81c72b342ffe 100644
--- a/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts
@@ -89,8 +89,6 @@ export interface RawPostgresPersonRepository {
): Promise<Map<string, number>>
fetchPersonDistinctIds(person: InternalPerson, limit?: number, tx?: TransactionClient): Promise<string[]>
- addPersonlessDistinctId(teamId: Team['id'], distinctId: string, tx?: TransactionClient): Promise<boolean>
- addPersonlessDistinctIdForMerge(teamId: Team['id'], distinctId: string, tx?: TransactionClient): Promise<boolean>
personPropertiesSize(personId: string, teamId: number): Promise<number>
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
index 9c9ecd4f762f..7c7e39711349 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
@@ -147,9 +147,6 @@ describe('BatchWritingPersonStore', () => {
deletePerson: jest.fn().mockResolvedValue([]),
addDistinctId: jest.fn().mockResolvedValue([]),
moveDistinctIds: jest.fn().mockResolvedValue({ success: true, messages: [], distinctIdsMoved: [] }),
- addPersonlessDistinctId: jest.fn().mockResolvedValue(true),
- addPersonlessDistinctIdForMerge: jest.fn().mockResolvedValue(true),
- addPersonlessDistinctIdsBatch: jest.fn().mockResolvedValue(new Map()),
personPropertiesSize: jest.fn().mockResolvedValue(1024),
updateCohortsAndFeatureFlagsForMerge: jest.fn().mockResolvedValue(undefined),
inTransaction: jest.fn().mockImplementation(async (description, transaction) => {
@@ -171,7 +168,6 @@ describe('BatchWritingPersonStore', () => {
moveDistinctIdsFromPersons: jest
.fn()
.mockResolvedValue({ success: true, messages: [], distinctIdsMoved: [] }),
- addPersonlessDistinctIdForMerge: jest.fn().mockResolvedValue(true),
updateCohortsAndFeatureFlagsForMerge: jest.fn().mockResolvedValue(undefined),
updateCohortsAndFeatureFlagsForMergeBatch: jest.fn().mockResolvedValue(undefined),
countDistinctIdsForPersons: jest.fn().mockResolvedValue(new Map()),
@@ -1522,52 +1518,6 @@ describe('BatchWritingPersonStore', () => {
})
})
- describe('addPersonlessDistinctId', () => {
- it('should call repository method and return result', async () => {
- const mockRepo = createMockRepository()
- const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)
-
- const result = await personStore.addPersonlessDistinctId(teamId, 'test-distinct', 0)
-
- expect(mockRepo.addPersonlessDistinctId).toHaveBeenCalledWith(teamId, 'test-distinct')
- expect(result).toBe(true)
- })
-
- it('should handle repository returning false', async () => {
- const mockRepo = createMockRepository()
- mockRepo.addPersonlessDistinctId = jest.fn().mockResolvedValue(false)
- const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)
-
- const result = await personStore.addPersonlessDistinctId(teamId, 'test-distinct', 0)
-
- expect(mockRepo.addPersonlessDistinctId).toHaveBeenCalledWith(teamId, 'test-distinct')
- expect(result).toBe(false)
- })
- })
-
- describe('addPersonlessDistinctIdForMerge', () => {
- it('should call repository method and return result', async () => {
- const mockRepo = createMockRepository()
- const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)
-
- const result = await personStore.addPersonlessDistinctIdForMerge(teamId, 'test-distinct', undefined, 0)
-
- expect(mockRepo.addPersonlessDistinctIdForMerge).toHaveBeenCalledWith(teamId, 'test-distinct')
- expect(result).toBe(true)
- })
-
- it('should handle repository returning false', async () => {
- const mockRepo = createMockRepository()
- mockRepo.addPersonlessDistinctIdForMerge = jest.fn().mockResolvedValue(false)
- const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)
-
- const result = await personStore.addPersonlessDistinctIdForMerge(teamId, 'test-distinct', undefined, 0)
-
- expect(mockRepo.addPersonlessDistinctIdForMerge).toHaveBeenCalledWith(teamId, 'test-distinct')
- expect(result).toBe(false)
- })
- })
-
describe('personPropertiesSize', () => {
it('should call repository method and return result', async () => {
const mockRepo = createMockRepository()
@@ -3244,26 +3194,6 @@ describe('BatchWritingPersonStore', () => {
expect(personStore.getCachedPersonForUpdateByPersonId(teamId, person.id)).toBeUndefined()
})
- it('clears personlessBatchResults for evicted distinct IDs', () => {
- personStore.setCheckCachedPerson(teamId, 'user-a', null, 0)
- ;(personStore as any)['personlessBatchResults'].set(`${teamId}:user-a`, true)
-
- personStore.releaseBatch(0)
-
- expect(personStore.getPersonlessBatchResult(teamId, 'user-a')).toBeUndefined()
- })
-
- it('evicts personlessBatchResults written via addPersonlessDistinctIdForMerge after batch release', async () => {
- const batchStore = new BatchBoundPersonsStore(personStore, 0)
-
- await batchStore.addPersonlessDistinctIdForMerge(teamId, 'lonely-merge-distinct')
- expect(personStore.getPersonlessBatchResult(teamId, 'lonely-merge-distinct')).toBe(true)
-
- personStore.releaseBatch(0)
-
- expect(personStore.getPersonlessBatchResult(teamId, 'lonely-merge-distinct')).toBeUndefined()
- })
-
it('tracks property-update cache writes through the batch-bound store', async () => {
const batchStore = new BatchBoundPersonsStore(personStore, 0)
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
index c556496b54d3..a410250fda99 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
@@ -62,8 +62,6 @@ type MethodName =
| 'fetchPersonDistinctIds'
| 'updateCohortsAndFeatureFlagsForMerge'
| 'updateCohortsAndFeatureFlagsForMergeBatch'
- | 'addPersonlessDistinctId'
- | 'addPersonlessDistinctIdForMerge'
| 'addPersonUpdateToBatch'
type UpdateType = 'updatePersonAssertVersion' | 'updatePersonNoAssert'
@@ -124,7 +122,6 @@ class BatchWritingPersonsCache {
private personCheckCache = new Map<string, InternalPerson | null>()
private distinctIdToPersonId = new Map<string, string>()
private personUpdateCache = new Map<string, PersonUpdate | null>()
- private personlessBatchResults = new Map<string, boolean>()
private batchDistinctKeys = new Map<number, Set<string>>()
private distinctKeyRefCount = new Map<string, number>()
private deferredEvictions = new Set<string>()
@@ -153,10 +150,6 @@ class BatchWritingPersonsCache {
return this.distinctIdToPersonId
}
- getPersonlessBatchResultsCache(): Map<string, boolean> {
- return this.personlessBatchResults
- }
-
getBatchDistinctKeys(): Map<number, Set<string>> {
return this.batchDistinctKeys
}
@@ -337,14 +330,6 @@ class BatchWritingPersonsCache {
this.personCheckCache.delete(cacheKey)
}
- setPersonlessBatchResult(teamId: number, distinctId: string, value: boolean): void {
- this.personlessBatchResults.set(this.getDistinctCacheKey(teamId, distinctId), value)
- }
-
- getPersonlessBatchResult(teamId: number, distinctId: string): boolean | undefined {
- return this.personlessBatchResults.get(this.getDistinctCacheKey(teamId, distinctId))
- }
-
releaseBatchId(batchId: number): void {
const keys = this.batchDistinctKeys.get(batchId)
if (this.pendingPrefetchesByBatchId.has(batchId)) {
@@ -438,7 +423,6 @@ class BatchWritingPersonsCache {
}
this.personCheckCache.delete(distinctKey)
- this.personlessBatchResults.delete(distinctKey)
}
private mergeUpdateIntoCachedPersonUpdate(existingPersonUpdate: PersonUpdate, person: PersonUpdate): PersonUpdate {
@@ -520,11 +504,6 @@ class BatchBoundPersonsCache {
this.cache.trackBatchEntry(this.batchId, teamId, distinctId)
this.cache.setDistinctIdToPersonId(teamId, distinctId, personId)
}
-
- setPersonlessBatchResult(teamId: number, distinctId: string, value: boolean): void {
- this.cache.trackBatchEntry(this.batchId, teamId, distinctId)
- this.cache.setPersonlessBatchResult(teamId, distinctId, value)
- }
}
/**
@@ -560,7 +539,6 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
personUpdateCache: { get: () => this.personCache.getUpdateCache() },
personCheckCache: { get: () => this.personCache.getCheckCache() },
distinctIdToPersonId: { get: () => this.personCache.getDistinctIdToPersonIdCache() },
- personlessBatchResults: { get: () => this.personCache.getPersonlessBatchResultsCache() },
batchDistinctKeys: { get: () => this.personCache.getBatchDistinctKeys() },
distinctKeyRefCount: { get: () => this.personCache.getDistinctKeyRefCount() },
})
@@ -1591,57 +1569,6 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
)
}
- async addPersonlessDistinctId(teamId: Team['id'], distinctId: string, batchId: number): Promise<boolean> {
- this.incrementCount('addPersonlessDistinctId', distinctId)
- const isMerged = await this.personRepository.addPersonlessDistinctId(teamId, distinctId)
- // Cache the result so later events for this distinct ID in the same batch skip the insert.
- this.personCache.obtainForBatchId(batchId).setPersonlessBatchResult(teamId, distinctId, isMerged)
- return isMerged
- }
-
- async addPersonlessDistinctIdForMerge(
- teamId: Team['id'],
- distinctId: string,
- tx: PersonRepositoryTransaction | undefined,
- batchId: number
- ): Promise<boolean> {
- this.incrementCount('addPersonlessDistinctIdForMerge', distinctId)
- const isMerged = await (tx || this.personRepository).addPersonlessDistinctIdForMerge(teamId, distinctId)
- // Update the batch results cache so processPersonlessStep knows this was merged
- if (isMerged) {
- this.personCache.obtainForBatchId(batchId).setPersonlessBatchResult(teamId, distinctId, true)
- }
- return isMerged
- }
-
- async processPersonlessDistinctIdsBatch(
- entries: { teamId: number; distinctId: string }[],
- batchId: number
- ): Promise<void> {
- if (entries.length === 0) {
- return
- }
-
- const cache = this.personCache.obtainForBatchId(batchId)
-
- const results = await this.personRepository.addPersonlessDistinctIdsBatch(entries)
- // Only store merged distinct IDs - these need force_upgrade handling.
- // Iterate entries (not result keys) to use the ':' cache key format consistently.
- for (const { teamId, distinctId } of entries) {
- if (results.get(`${teamId}|${distinctId}`)) {
- cache.setPersonlessBatchResult(teamId, distinctId, true)
- }
- }
- }
-
- // Returns the cached merge result for a distinct ID inserted earlier this batch:
- // true if the row was merged, false if addPersonlessDistinctId inserted it without a
- // merge, undefined if no insert was recorded. The batch and forMerge paths only cache
- // merged rows, so a non-merged insert from those paths also reads back as undefined.
- getPersonlessBatchResult(teamId: number, distinctId: string): boolean | undefined {
- return this.personCache.getPersonlessBatchResult(teamId, distinctId)
- }
-
async personPropertiesSize(personId: string, teamId: number): Promise<number> {
return await this.personRepository.personPropertiesSize(personId, teamId)
}
diff --git a/nodejs/src/ingestion/common/persons/person-context.ts b/nodejs/src/ingestion/common/persons/person-context.ts
index 2106a84e64e0..5c88407b531b 100644
--- a/nodejs/src/ingestion/common/persons/person-context.ts
+++ b/nodejs/src/ingestion/common/persons/person-context.ts
@@ -39,21 +39,6 @@ export type MergeEventsConfig = {
isTeamEnabled: ValueMatcher<number>
}
-/** Per-team gates for the personless-table removal rollout (steps 2-4 of the RFC). */
-export type PersonlessRolloutConfig = {
- /**
- * Always-v1: merge-added distinct id mappings get version 1 unconditionally (always writing a
- * ClickHouse override) instead of consulting posthog_personlessdistinctid.
- */
- mergeAlwaysV1: boolean
- /**
- * Stop-reading/stop-writing: merges skip the posthog_personlessdistinctid upserts entirely.
- * Forces mergeAlwaysV1 (normalized in the PersonContext constructor): without the upserts the
- * table has gaps for this team, so a version decision must never consult it again.
- */
- writesDisabled: boolean
-}
-
/**
* Lightweight data holder containing all the context needed for person processing.
* This replaces the previous PersonState class which mixed data and business logic.
@@ -79,18 +64,10 @@ export class PersonContext {
partitionCount: 64,
isTeamEnabled: () => false,
},
- public readonly personlessRollout: PersonlessRolloutConfig = {
- mergeAlwaysV1: false,
- writesDisabled: false,
- },
/** Fold plan shared by this event's consecutive $identify run; see person-merge-fold.ts. */
public readonly mergeFoldPlan?: MergeFoldPlan
) {
this.eventProperties = event.properties!
- this.personlessRollout = {
- mergeAlwaysV1: personlessRollout.mergeAlwaysV1 || personlessRollout.writesDisabled,
- writesDisabled: personlessRollout.writesDisabled,
- }
}
async produceMessages(messages: PersonMessage[]): Promise<void> {
diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.ts
index 8084e4101e10..345db05cfff8 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts
@@ -64,8 +64,8 @@ export const mergeFoldSizeHistogram = new Histogram({
export const mergeDistinctIdOverrideCounter = new Counter({
name: 'person_merge_distinct_id_override_total',
- help: 'Distinct id mapping rows written during merges, split by whether their version writes a ClickHouse override row.',
- labelNames: ['call', 'overrideWritten'],
+ help: 'Distinct id mapping rows written during merges, each writing a ClickHouse override row.',
+ labelNames: ['call'],
})
/** Thrown inside the fold transaction to roll it back when merge-mode move bounds would be exceeded. */
@@ -226,32 +226,16 @@ export class PersonMergeService {
// A note about the `distinctIdVersion` logic you'll find below:
//
- // Historically, we always INSERT-ed new `posthog_persondistinctid` rows with `version=0`.
- // Overrides are only created when the version is > 0, see:
+ // Overrides are only created for `posthog_persondistinctid` rows with version > 0, see:
// https://github.com/PostHog/posthog/blob/92e17ce307a577c4233d4ab252eebc6c2207a5ee/posthog/models/person/sql.py#L269-L287
//
- // With the addition of optional person profile processing, we are no longer creating
- // `posthog_persondistinctid` and `posthog_person` rows when $process_person_profile=false.
- // This means that at merge time, it's possible this `distinct_id` and its deterministically
- // generated `person.uuid` has already been used for events in ClickHouse, but they have no
- // corresponding rows in the `posthog_persondistinctid` or `posthog_person` tables.
- //
- // For this reason, $process_person_profile=false write to the `posthog_personlessdistinctid`
- // table just to note that a given Distinct ID was used for "personless" mode. Then, during
- // our merges transactions below, we do two things:
- // 1. We check whether a row exists in `posthog_personlessdistinctid` for that Distinct ID,
- // if so, we need to write out `posthog_persondistinctid` rows with `version=1` so that
- // an override is created in ClickHouse which will associate the old "personless" events
- // with the Person UUID they were merged into.
- // 2. We insert and/or update the `posthog_personlessdistinctid` ourselves, to mark that
- // the Distinct ID has been merged. This is important so that an event being processed
- // concurrently for that Distinct ID doesn't emit an event and _miss_ that a different
- // Person UUID needs to be used now. (See the `processPerson` code in `update` for more.)
- //
- // When `mergeAlwaysV1` is on for the team, check 1 is skipped: every merge-added mapping
- // gets version 1 regardless of personless history. Version 1 is safe in both cases — the
- // override either re-points real personless events or is a harmless transient row the
- // squash job deletes. The upsert (check 2) still runs for the `is_merged` race hint.
+ // With $process_person_profile=false, events can exist in ClickHouse stamped with the
+ // deterministic implied person uuid even though no `posthog_persondistinctid` or
+ // `posthog_person` rows exist. So every merge-added mapping for a distinct id without a
+ // person gets version 1: the override either re-points real personless events or is a
+ // harmless transient row the squash job deletes within days. The exception is the distinct
+ // id whose uuid a newly created person is born on — its events already point at the right
+ // person, so it keeps version 0 and stays out of the overrides join.
if ((otherPerson && !mergeIntoPerson) || (!otherPerson && mergeIntoPerson)) {
// Only one of the two Distinct IDs points at an existing Person
@@ -267,11 +251,8 @@ export class PersonMergeService {
this.discardOverrideCounts()
const result = await this.context.personStore.inTransaction('mergeDistinctIds-OneExists', async (tx) => {
// See comment above about `distinctIdVersion`
- const insertedDistinctId = this.context.personlessRollout.writesDisabled
- ? false
- : await tx.addPersonlessDistinctIdForMerge(this.context.team.id, distinctIdToAdd)
- const distinctIdVersion = this.context.personlessRollout.mergeAlwaysV1 || !insertedDistinctId ? 1 : 0
- this.recordOverrideCount('oneExists', distinctIdVersion > 0)
+ const distinctIdVersion = 1
+ this.recordOverrideCount('oneExists')
const kafkaMessages = await tx.addDistinctId(existingPerson, distinctIdToAdd, distinctIdVersion)
await this.context.produceMessages(kafkaMessages)
@@ -298,52 +279,16 @@ export class PersonMergeService {
} else {
// Neither Distinct ID points at an existing Person
- let distinctId1 = mergeIntoDistinctId
- let distinctId2 = otherPersonDistinctId
+ const distinctId1 = mergeIntoDistinctId
+ const distinctId2 = otherPersonDistinctId
this.discardOverrideCounts()
const result = await this.context.personStore.inTransaction('mergeDistinctIds-NeitherExist', async (tx) => {
- // See comment above about `distinctIdVersion`. With personless writes disabled the
- // upserts are skipped; the always-v1 branch below never reads the results.
- const insertedDistinctId1 = this.context.personlessRollout.writesDisabled
- ? false
- : await tx.addPersonlessDistinctIdForMerge(this.context.team.id, distinctId1)
- const insertedDistinctId2 = this.context.personlessRollout.writesDisabled
- ? false
- : await tx.addPersonlessDistinctIdForMerge(this.context.team.id, distinctId2)
-
- // `createPerson` uses the first Distinct ID provided to generate the Person
- // UUID. That means the first Distinct ID definitely doesn't need an override,
- // and can always use version 0. Below, we exhaust all of the options to decide
- // whether we can optimize away an override by doing a swap, or whether we
- // need to actually write an override. (But mostly we're being verbose for
- // documentation purposes)
- let distinctId2Version = 0
- if (this.context.personlessRollout.mergeAlwaysV1) {
- // The upsert results are not consulted: the second Distinct ID always gets an
- // override, and no swap is needed since the first one derives the Person UUID.
- distinctId2Version = 1
- } else if (insertedDistinctId1 && insertedDistinctId2) {
- // We were the first to insert both (neither was used for Personless), so we
- // can use either as the primary Person UUID and create no overrides.
- } else if (insertedDistinctId1 && !insertedDistinctId2) {
- // We created 1, but 2 was already used for Personless. Let's swap so
- // that 2 can be the primary Person UUID and no override is needed.
- ;[distinctId1, distinctId2] = [distinctId2, distinctId1]
- } else if (!insertedDistinctId1 && insertedDistinctId2) {
- // We created 2, but 1 was already used for Personless, so we want to
- // use 1 as the primary Person UUID so that no override is needed.
- } else if (!insertedDistinctId1 && !insertedDistinctId2) {
- // Both were used in Personless mode, so there is no more-correct choice of
- // primary Person UUID to make here, and we need to drop an override by
- // using version = 1 for Distinct ID 2.
- distinctId2Version = 1
- }
-
- // The first Distinct ID is used to create the new Person's UUID, and so it
- // never needs an override.
+ // See comment above about `distinctIdVersion`: the first Distinct ID derives the
+ // new Person's UUID so it never needs an override; the second always gets one.
const distinctId1Version = 0
- this.recordOverrideCount('neitherExist', distinctId2Version > 0)
+ const distinctId2Version = 1
+ this.recordOverrideCount('neitherExist')
const [person, wasCreated] = await this.personCreateService.createPerson(
timestamp,
@@ -611,16 +556,13 @@ export class PersonMergeService {
if (moveResult.distinctIdsMoved.length !== expectedMoveCount) {
throw new MergeFoldConflictError('folded merge moved an unexpected number of distinct ids')
}
- this.recordOverrideCount('bothExistMove', true, moveResult.distinctIdsMoved.length)
+ this.recordOverrideCount('bothExistMove', moveResult.distinctIdsMoved.length)
const addMessages: PersonMessage[] = []
for (const pair of missingPairs) {
- // See mergeDistinctIds for the personless distinctIdVersion logic.
- const inserted = this.context.personlessRollout.writesDisabled
- ? false
- : await tx.addPersonlessDistinctIdForMerge(teamId, pair.anonDistinctId)
- const distinctIdVersion = this.context.personlessRollout.mergeAlwaysV1 || !inserted ? 1 : 0
- this.recordOverrideCount('fold', distinctIdVersion > 0)
+ // See mergeDistinctIds for the distinctIdVersion logic.
+ const distinctIdVersion = 1
+ this.recordOverrideCount('fold')
addMessages.push(...(await tx.addDistinctId(person, pair.anonDistinctId, distinctIdVersion)))
}
@@ -876,11 +818,11 @@ export class PersonMergeService {
// Override-counter increments are buffered and flushed only after the enclosing
// transaction commits: merges retry and roll back, and rolled-back rows must not
// inflate a metric used for override-inflow capacity planning.
- private pendingOverrideCounts: { call: string; overrideWritten: boolean; count: number }[] = []
+ private pendingOverrideCounts: { call: string; count: number }[] = []
- private recordOverrideCount(call: string, overrideWritten: boolean, count: number = 1): void {
+ private recordOverrideCount(call: string, count: number = 1): void {
if (count > 0) {
- this.pendingOverrideCounts.push({ call, overrideWritten, count })
+ this.pendingOverrideCounts.push({ call, count })
}
}
@@ -889,8 +831,8 @@ export class PersonMergeService {
}
private flushOverrideCounts(): void {
- for (const { call, overrideWritten, count } of this.pendingOverrideCounts) {
- mergeDistinctIdOverrideCounter.labels({ call, overrideWritten: String(overrideWritten) }).inc(count)
+ for (const { call, count } of this.pendingOverrideCounts) {
+ mergeDistinctIdOverrideCounter.labels({ call }).inc(count)
}
this.pendingOverrideCounts = []
}
@@ -951,7 +893,7 @@ export class PersonMergeService {
} else {
allDistinctIdMessages.push(...distinctIdResult.messages)
hasProcessedAnyDistinctIds = true
- this.recordOverrideCount('bothExistMove', true, distinctIdResult.distinctIdsMoved.length)
+ this.recordOverrideCount('bothExistMove', distinctIdResult.distinctIdsMoved.length)
// Check if we moved fewer than the batch size, indicating we're done
hasMore = distinctIdResult.distinctIdsMoved.length >= batchSize
@@ -1001,7 +943,7 @@ export class PersonMergeService {
throw new PersonMergeLimitExceededError('person_merge_move_limit_hit')
}
}
- this.recordOverrideCount('bothExistMove', true, movedCount)
+ this.recordOverrideCount('bothExistMove', movedCount)
return allDistinctIdMessages
}
diff --git a/nodejs/src/ingestion/common/persons/personless-distinct-id-cache.ts b/nodejs/src/ingestion/common/persons/personless-distinct-id-cache.ts
deleted file mode 100644
index 782f0f907956..000000000000
--- a/nodejs/src/ingestion/common/persons/personless-distinct-id-cache.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { LRUCache } from 'lru-cache'
-import { Counter } from 'prom-client'
-
-import { ONE_HOUR } from '~/common/config/constants'
-
-export const personlessDistinctIdCacheOperationsCounter = new Counter({
- name: 'personless_distinct_id_cache_operations_total',
- help: 'Number of cache hits and misses for the personless distinct ID inserted cache',
- // `source` separates the batched personless step from the per-event $feature_flag_called
- // path so a high-volume flag-called miss rate can be read on its own during rollout.
- labelNames: ['operation', 'source'],
-})
-
-// Tracks whether we know we've already inserted a `posthog_personlessdistinctid` for the given
-// (team_id, distinct_id) pair. If we have, then we can skip the INSERT attempt.
-const PERSONLESS_DISTINCT_ID_INSERTED_CACHE = new LRUCache<string, boolean>({
- max: 100_000,
- ttl: ONE_HOUR * 4,
- updateAgeOnGet: true,
-})
-
-export function hasInsertedPersonlessDistinctId(teamId: number, distinctId: string): boolean {
- return PERSONLESS_DISTINCT_ID_INSERTED_CACHE.get(`${teamId}|${distinctId}`) === true
-}
-
-export function markPersonlessDistinctIdInserted(teamId: number, distinctId: string): void {
- PERSONLESS_DISTINCT_ID_INSERTED_CACHE.set(`${teamId}|${distinctId}`, true)
-}
diff --git a/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts b/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts
index a423de3ae7d8..659f02b505ab 100644
--- a/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts
@@ -81,8 +81,6 @@ export interface PersonsStoreTransactionForBatch {
distinctId: string
): Promise<void>
- addPersonlessDistinctIdForMerge(teamId: number, distinctId: string): Promise<boolean>
-
fetchPersonDistinctIds(person: InternalPerson, distinctId: string, limit?: number): Promise<string[]>
}
@@ -105,10 +103,7 @@ export type PersonsStoreForBatch = Omit<
| 'addDistinctId'
| 'moveDistinctIds'
| 'moveDistinctIdsFromPersons'
- | 'addPersonlessDistinctId'
- | 'addPersonlessDistinctIdForMerge'
| 'prefetchPersons'
- | 'processPersonlessDistinctIdsBatch'
| 'releaseBatch'
| 'getFlushStats'
| 'inTransaction'
@@ -150,12 +145,6 @@ export type PersonsStoreForBatch = Omit<
tx?: PersonRepositoryTransaction
): Promise<[InternalPerson, PersonMessage[], boolean]>
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>
- addPersonlessDistinctId(teamId: number, distinctId: string): Promise<boolean>
- addPersonlessDistinctIdForMerge(
- teamId: number,
- distinctId: string,
- tx?: PersonRepositoryTransaction
- ): Promise<boolean>
moveDistinctIds(
source: InternalPerson,
target: InternalPerson,
@@ -164,7 +153,6 @@ export type PersonsStoreForBatch = Omit<
tx: PersonRepositoryTransaction
): Promise<MoveDistinctIdsResult>
prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void>
- processPersonlessDistinctIdsBatch(entries: { teamId: number; distinctId: string }[]): Promise<void>
inTransaction<T>(description: string, transaction: (tx: PersonsStoreTransactionForBatch) => Promise<T>): Promise<T>
readonly batchId: number
}
@@ -284,10 +272,6 @@ class BatchBoundPersonsStoreTransaction implements PersonsStoreTransactionForBat
return this.tx.updateCohortsAndFeatureFlagsForMergeBatch(teamID, sourcePersonIDs, targetPersonID, distinctId)
}
- addPersonlessDistinctIdForMerge(teamId: number, distinctId: string): Promise<boolean> {
- return this.tx.addPersonlessDistinctIdForMerge(teamId, distinctId, this.batchId)
- }
-
fetchPersonDistinctIds(person: InternalPerson, distinctId: string, limit?: number): Promise<string[]> {
return this.tx.fetchPersonDistinctIds(person, distinctId, limit)
}
@@ -399,10 +383,6 @@ export class BatchBoundPersonsStore implements PersonsStoreForBatch {
return this.store.prefetchPersons(teamDistinctIds)
}
- processPersonlessDistinctIdsBatch(entries: { teamId: number; distinctId: string }[]): Promise<void> {
- return this.store.processPersonlessDistinctIdsBatch(entries, this.batchId)
- }
-
inTransaction<T>(
description: string,
transaction: (tx: PersonsStoreTransactionForBatch) => Promise<T>
@@ -460,18 +440,6 @@ export class BatchBoundPersonsStore implements PersonsStoreForBatch {
return this.store.updateCohortsAndFeatureFlagsForMerge(teamID, sourcePersonID, targetPersonID, distinctId, tx)
}
- addPersonlessDistinctId(teamId: number, distinctId: string): Promise<boolean> {
- return this.store.addPersonlessDistinctId(teamId, distinctId, this.batchId)
- }
-
- addPersonlessDistinctIdForMerge(
- teamId: number,
- distinctId: string,
- tx?: PersonRepositoryTransaction
- ): Promise<boolean> {
- return this.store.addPersonlessDistinctIdForMerge(teamId, distinctId, tx, this.batchId)
- }
-
personPropertiesSize(personId: string, teamId: number): Promise<number> {
return this.store.personPropertiesSize(personId, teamId)
}
@@ -489,10 +457,6 @@ export class BatchBoundPersonsStore implements PersonsStoreForBatch {
return this.store.removeDistinctIdFromCache(teamId, distinctId)
}
- getPersonlessBatchResult(teamId: number, distinctId: string): boolean | undefined {
- return this.store.getPersonlessBatchResult(teamId, distinctId)
- }
-
flush(): Promise<FlushResult[]> {
return this.store.flush()
}
diff --git a/nodejs/src/ingestion/common/persons/persons-store-transaction.ts b/nodejs/src/ingestion/common/persons/persons-store-transaction.ts
index 189f3a135b3d..3a64d316f483 100644
--- a/nodejs/src/ingestion/common/persons/persons-store-transaction.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store-transaction.ts
@@ -151,10 +151,6 @@ export class PersonsStoreTransaction {
)
}
- async addPersonlessDistinctIdForMerge(teamId: number, distinctId: string, batchId: number): Promise<boolean> {
- return await this.store.addPersonlessDistinctIdForMerge(teamId, distinctId, this.tx, batchId)
- }
-
async fetchPersonDistinctIds(person: InternalPerson, distinctId: string, limit?: number): Promise<string[]> {
return await this.store.fetchPersonDistinctIds(person, distinctId, limit, this.tx)
}
diff --git a/nodejs/src/ingestion/common/persons/persons-store.ts b/nodejs/src/ingestion/common/persons/persons-store.ts
index 7ecefdddeefe..c0140756d88f 100644
--- a/nodejs/src/ingestion/common/persons/persons-store.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store.ts
@@ -170,21 +170,6 @@ export interface PersonsStore extends BatchWritingStore<FlushResult> {
tx?: PersonRepositoryTransaction
): Promise<void>
- /**
- * Adds a personless distinct ID
- */
- addPersonlessDistinctId(teamId: number, distinctId: string, batchId: number): Promise<boolean>
-
- /**
- * Adds a personless distinct ID during merge
- */
- addPersonlessDistinctIdForMerge(
- teamId: number,
- distinctId: string,
- tx: PersonRepositoryTransaction | undefined,
- batchId: number
- ): Promise<boolean>
-
/**
* Returns the size of the person properties
*/
@@ -220,20 +205,6 @@ export interface PersonsStore extends BatchWritingStore<FlushResult> {
*/
prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void>
- /**
- * Batch-inserts personless distinct IDs for events where no person exists.
- * Stores is_merged results in a cache for later lookup.
- * @param entries - A list of team IDs and distinct IDs to insert
- * @param batchId - Batch ID for cache eviction tracking
- */
- processPersonlessDistinctIdsBatch(entries: { teamId: number; distinctId: string }[], batchId: number): Promise<void>
-
- /**
- * Gets the is_merged result from batch personless insert.
- * Returns undefined if not in batch cache.
- */
- getPersonlessBatchResult(teamId: number, distinctId: string): boolean | undefined
-
/**
* Flushes the batch
*/
diff --git a/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts b/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts
index 1fb63353a9c9..7797e11d6c68 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts
@@ -8,10 +8,6 @@ export interface EventPipelineRunnerOptions {
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: string
PERSON_MERGE_FOLD_ENABLED: boolean
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: string
- /** Teams whose merge-added distinct id mappings always get version 1: '*' for all, '' to disable, or comma-separated team IDs */
- PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: string
- /** Teams with personless-table writes and is_merged reads disabled (implies always-v1): '*' for all, '' to disable, or comma-separated team IDs */
- PERSONLESS_WRITES_DISABLED_TEAMS: string
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: number
PERSON_PROPERTIES_UPDATE_ALL: boolean
/** Teams whose $feature_flag_called events default to personless: '*' for all, '' to disable, or comma-separated team IDs */
diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.test.ts
index 902708344cc7..2ddb5ecfa20a 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.test.ts
@@ -253,9 +253,7 @@ describe('createProcessPersonlessStep', () => {
expect(fetchForCheckingSpy).not.toHaveBeenCalled()
})
- it('defaults to personless and records the distinct ID when no person exists', async () => {
- const addPersonlessDistinctIdSpy = jest.spyOn(personsStore, 'addPersonlessDistinctId')
-
+ it('defaults to personless when no person exists', async () => {
const step = buildStep()
const result = await step(
createInput({
@@ -273,62 +271,10 @@ describe('createProcessPersonlessStep', () => {
expect(result.value.normalizedEvent.properties?.$set).toBeUndefined()
expect(result.value.normalizedEvent.properties?.$process_person_profile).toBe(false)
}
- expect(addPersonlessDistinctIdSpy).toHaveBeenCalledWith(teamId, pluginEvent.distinct_id, 0)
- })
-
- it('skips the personless distinct ID insert when the batch already has a result', async () => {
- jest.spyOn(personsStore, 'getPersonlessBatchResult').mockReturnValue(false)
- const addPersonlessDistinctIdSpy = jest.spyOn(personsStore, 'addPersonlessDistinctId')
-
- const step = buildStep()
- const result = await step(createInput({ processPerson: true, normalizedEvent: flagCalledEvent() }))
-
- expect(result.type).toBe(PipelineResultType.OK)
- if (isOkResult(result)) {
- expect(result.value.processPerson).toBe(false)
- }
- expect(addPersonlessDistinctIdSpy).not.toHaveBeenCalled()
- })
-
- it('keeps the event personful when the distinct ID turns out to be merged', async () => {
- const personUuid = new UUIDT().toString()
- const person = await createPerson(infra, timestamp, {}, {}, {}, teamId, null, false, personUuid, {
- distinctId: 'merge-target',
- })
-
- jest.spyOn(personsStore, 'fetchForChecking').mockResolvedValue(null)
- jest.spyOn(personsStore, 'addPersonlessDistinctId').mockResolvedValue(true)
- const fetchForUpdateSpy = jest.spyOn(personsStore, 'fetchForUpdate').mockResolvedValue(person)
-
- const step = buildStep()
- const result = await step(createInput({ processPerson: true, normalizedEvent: flagCalledEvent() }))
-
- expect(result.type).toBe(PipelineResultType.OK)
- if (isOkResult(result)) {
- expect(result.value.processPerson).toBe(true)
- expect(result.value.personlessPerson).toBeUndefined()
- }
- expect(fetchForUpdateSpy).toHaveBeenCalledWith(teamId, pluginEvent.distinct_id, 0)
- })
-
- it('defaults to personless when the merged person cannot be fetched from the leader', async () => {
- jest.spyOn(personsStore, 'fetchForChecking').mockResolvedValue(null)
- jest.spyOn(personsStore, 'addPersonlessDistinctId').mockResolvedValue(true)
- jest.spyOn(personsStore, 'fetchForUpdate').mockResolvedValue(null)
-
- const step = buildStep()
- const result = await step(createInput({ processPerson: true, normalizedEvent: flagCalledEvent() }))
-
- expect(result.type).toBe(PipelineResultType.OK)
- if (isOkResult(result)) {
- expect(result.value.processPerson).toBe(false)
- expect(result.value.personlessPerson).toBeDefined()
- }
})
it('takes the generic personless path, not the defaulting branch, when already force-disabled', async () => {
const fetchForCheckingSpy = jest.spyOn(personsStore, 'fetchForChecking')
- const addPersonlessDistinctIdSpy = jest.spyOn(personsStore, 'addPersonlessDistinctId')
const step = buildStep()
const result = await step(
@@ -340,7 +286,6 @@ describe('createProcessPersonlessStep', () => {
expect(result.value.personlessPerson).toBeDefined()
}
expect(fetchForCheckingSpy).not.toHaveBeenCalled()
- expect(addPersonlessDistinctIdSpy).not.toHaveBeenCalled()
})
// Pipes an event through the same normalization steps that precede the personless
@@ -397,8 +342,6 @@ describe('createProcessPersonlessStep', () => {
})
it('skips the defaulting branch for explicit $process_person_profile=false events', async () => {
- const addPersonlessDistinctIdSpy = jest.spyOn(personsStore, 'addPersonlessDistinctId')
-
const personlessStep = buildStep()
const normalized = await runThroughNormalization(flagCalledEvent({ $process_person_profile: false }))
@@ -409,8 +352,6 @@ describe('createProcessPersonlessStep', () => {
expect(result.value.processPerson).toBe(false)
expect(result.value.personlessPerson).toBeDefined()
}
- // The plain personless path leaves the insert to the batch step.
- expect(addPersonlessDistinctIdSpy).not.toHaveBeenCalled()
})
})
@@ -448,78 +389,6 @@ describe('createProcessPersonlessStep', () => {
expect(person.force_upgrade).toBeUndefined()
}
})
-
- it('checks batch result for personless distinct ID when no person exists', async () => {
- const getPersonlessBatchResultSpy = jest.spyOn(personsStore, 'getPersonlessBatchResult')
-
- const step = buildStep()
- await step(createInput())
-
- expect(getPersonlessBatchResultSpy).toHaveBeenCalledWith(teamId, pluginEvent.distinct_id)
- })
-
- it('returns fake person when batch result indicates no merge', async () => {
- jest.spyOn(personsStore, 'getPersonlessBatchResult').mockReturnValue(false)
-
- const step = buildStep()
- const result = await step(createInput())
-
- expect(result.type).toBe(PipelineResultType.OK)
- if (isOkResult(result)) {
- const person = result.value.personlessPerson!
- expect(person.created_at.toISO()).toBe('1970-01-01T00:00:05.000Z')
- }
- })
- })
-
- describe('personless writes disabled', () => {
- const buildGatedStep = () => createProcessPersonlessStep('*', '*')
-
- it('ignores the is_merged race hint and stays personless', async () => {
- const personUuid = new UUIDT().toString()
- const person = await createPerson(infra, timestamp, {}, {}, {}, teamId, null, false, personUuid, {
- distinctId: 'merge-target',
- })
-
- // A concurrent merge left an is_merged hint; with the gate on it is never read, so the
- // event stays on the implied person id and the always-written override corrects it later.
- jest.spyOn(personsStore, 'getPersonlessBatchResult').mockReturnValue(true)
- const fetchForUpdateSpy = jest.spyOn(personsStore, 'fetchForUpdate').mockResolvedValue(person)
-
- const step = buildGatedStep()
- const result = await step(createInput())
-
- expect(result.type).toBe(PipelineResultType.OK)
- if (isOkResult(result)) {
- const returnedPerson = result.value.personlessPerson!
- expect(returnedPerson.uuid).not.toBe(personUuid)
- expect(returnedPerson.created_at.toISO()).toBe('1970-01-01T00:00:05.000Z')
- }
- expect(fetchForUpdateSpy).not.toHaveBeenCalled()
- })
-
- it('defaults $feature_flag_called to personless without recording the distinct ID', async () => {
- const addPersonlessDistinctIdSpy = jest.spyOn(personsStore, 'addPersonlessDistinctId')
-
- const step = buildGatedStep()
- const result = await step(
- createInput({
- processPerson: true,
- normalizedEvent: {
- ...pluginEvent,
- event: '$feature_flag_called',
- properties: { $feature_flag: 'new-homepage', $feature_flag_response: 'test' },
- },
- })
- )
-
- expect(result.type).toBe(PipelineResultType.OK)
- if (isOkResult(result)) {
- expect(result.value.processPerson).toBe(false)
- expect(result.value.personlessPerson).toBeDefined()
- }
- expect(addPersonlessDistinctIdSpy).not.toHaveBeenCalled()
- })
})
describe('force_upgrade logic', () => {
@@ -583,40 +452,9 @@ describe('createProcessPersonlessStep', () => {
})
})
- describe('merge detection', () => {
- it('detects when person was merged and re-fetches from leader', async () => {
- const personUuid = new UUIDT().toString()
- const personCreatedAt = DateTime.fromISO('2020-02-20T00:00:00Z')
-
- const person = await createPerson(
- infra,
- personCreatedAt,
- { name: 'John' },
- {},
- {},
- teamId,
- null,
- false,
- personUuid,
- { distinctId: pluginEvent.distinct_id }
- )
-
- jest.spyOn(personsStore, 'fetchForChecking').mockResolvedValueOnce(null)
- jest.spyOn(personsStore, 'getPersonlessBatchResult').mockReturnValue(true)
- const fetchForUpdateSpy = jest.spyOn(personsStore, 'fetchForUpdate').mockResolvedValue(person)
-
- const step = buildStep()
- const result = await step(createInput())
-
- expect(result.type).toBe(PipelineResultType.OK)
- expect(fetchForUpdateSpy).toHaveBeenCalledWith(teamId, pluginEvent.distinct_id, 0)
- })
- })
-
describe('forceDisablePersonProcessing', () => {
it('skips all DB operations and returns fake person immediately when true', async () => {
const fetchForCheckingSpy = jest.spyOn(personsStore, 'fetchForChecking')
- const getPersonlessBatchResultSpy = jest.spyOn(personsStore, 'getPersonlessBatchResult')
const step = buildStep()
const result = await step(createInput({ forceDisablePersonProcessing: true }))
@@ -630,7 +468,6 @@ describe('createProcessPersonlessStep', () => {
}
expect(fetchForCheckingSpy).not.toHaveBeenCalled()
- expect(getPersonlessBatchResultSpy).not.toHaveBeenCalled()
})
it('performs normal processing when false', async () => {
diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.ts b/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.ts
index 29ab8c0e5499..87ead7c71170 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.ts
@@ -1,17 +1,11 @@
import { DateTime } from 'luxon'
-import { buildIntegerMatcher } from '~/common/config/config'
import { normalizeProcessPerson } from '~/common/utils/event'
import {
buildFlagCalledPersonlessMatcher,
isFlagCalledPersonlessCandidate,
} from '~/ingestion/common/persons/flag-called-personless'
import { uuidFromDistinctId } from '~/ingestion/common/persons/person-uuid'
-import {
- hasInsertedPersonlessDistinctId,
- markPersonlessDistinctIdInserted,
- personlessDistinctIdCacheOperationsCounter,
-} from '~/ingestion/common/persons/personless-distinct-id-cache'
import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
import { DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS } from '~/ingestion/config'
import { PipelineResult, ok } from '~/ingestion/framework/results'
@@ -43,16 +37,13 @@ export type ProcessPersonlessOutput = {
*
* For personless events, this step:
* 1. Fetches existing person from cache (populated by prefetchPersonsStep)
- * 2. Checks batch results for is_merged flag (populated by processPersonlessDistinctIdsChunkStep)
- * 3. Calculates force_upgrade flag
- * 4. Returns person (real or fake) with potential force_upgrade flag
+ * 2. Calculates force_upgrade flag
+ * 3. Returns person (real or fake) with potential force_upgrade flag
*/
export function createProcessPersonlessStep<TInput extends ProcessPersonlessInput>(
- flagCalledPersonlessDefaultTeams: string = DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,
- personlessWritesDisabledTeams: string = ''
+ flagCalledPersonlessDefaultTeams: string = DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS
): ProcessingStep<TInput, TInput & ProcessPersonlessOutput> {
const flagCalledDefaultEnabledForTeam = buildFlagCalledPersonlessMatcher(flagCalledPersonlessDefaultTeams)
- const writesDisabledForTeam = buildIntegerMatcher(personlessWritesDisabledTeams, true)
return async function processPersonlessStep(
input: TInput
@@ -69,11 +60,7 @@ export function createProcessPersonlessStep<TInput extends ProcessPersonlessInpu
return ok(input)
}
- return await applyFeatureFlagCalledPersonlessDefault(
- input,
- input.personsStoreForBatch,
- writesDisabledForTeam(input.team.id)
- )
+ return await applyFeatureFlagCalledPersonlessDefault(input, input.personsStoreForBatch)
}
const { normalizedEvent, team, timestamp, forceDisablePersonProcessing, personsStoreForBatch } = input
@@ -83,25 +70,10 @@ export function createProcessPersonlessStep<TInput extends ProcessPersonlessInpu
return ok({ ...input, personlessPerson: createFakePerson(team.id, distinctId) })
}
- // Check if a real person exists for this distinct_id (from prefetch cache)
- let existingPerson = await personsStoreForBatch.fetchForChecking(team.id, distinctId)
-
- if (!existingPerson && !writesDisabledForTeam(team.id)) {
- // Check if batch insert found this distinct_id was merged
- // The chunk step (processPersonlessDistinctIdsChunkStep) already did the INSERT
- // and stored is_merged=true results in the personsStore cache.
- // With personless writes disabled (stop-reading rollout) the hint is skipped: an
- // event racing a merge stays propertyless and the always-written override
- // re-points it instead.
- const personIsMerged = personsStoreForBatch.getPersonlessBatchResult(team.id, distinctId)
-
- if (personIsMerged) {
- // If is_merged came back true, it means the posthog_personlessdistinctid
- // was updated by a merge. We need to fetch the person again (using the leader)
- // so that we properly associate this event with the Person we got merged into.
- existingPerson = await personsStoreForBatch.fetchForUpdate(team.id, distinctId)
- }
- }
+ // Check if a real person exists for this distinct_id (from prefetch cache). An event
+ // racing a merge may miss the person and stay propertyless; the merge's always-written
+ // override re-points it.
+ const existingPerson = await personsStoreForBatch.fetchForChecking(team.id, distinctId)
if (existingPerson) {
const person = existingPerson as Person
@@ -134,40 +106,12 @@ export function createProcessPersonlessStep<TInput extends ProcessPersonlessInpu
*/
async function applyFeatureFlagCalledPersonlessDefault<TInput extends ProcessPersonlessInput>(
input: TInput,
- personsStore: PersonsStoreForBatch,
- personlessWritesDisabled: boolean
+ personsStore: PersonsStoreForBatch
): Promise<PipelineResult<TInput & ProcessPersonlessOutput>> {
const { normalizedEvent, team } = input
const distinctId = normalizedEvent.distinct_id
- let existingPerson = await personsStore.fetchForChecking(team.id, distinctId)
-
- if (!existingPerson && !personlessWritesDisabled) {
- let personIsMerged = personsStore.getPersonlessBatchResult(team.id, distinctId)
-
- if (personIsMerged === undefined) {
- if (hasInsertedPersonlessDistinctId(team.id, distinctId)) {
- // The LRU keeps repeat distinct IDs from re-inserting on every event; a stale
- // hit just means the event goes personless, the same trade-off the batch step
- // accepts.
- personlessDistinctIdCacheOperationsCounter.inc({ operation: 'hit', source: 'flag_called' })
- } else {
- personlessDistinctIdCacheOperationsCounter.inc({ operation: 'miss', source: 'flag_called' })
- // The chunk step (processPersonlessDistinctIdsChunkStep) pre-inserts flag_called
- // rows when enabled, but it may be disabled or this distinct ID may be first-seen,
- // so record it here when the LRU shows no prior insert. Without the row, a later
- // identify/merge would never re-point these events at the merged person.
- personIsMerged = await personsStore.addPersonlessDistinctId(team.id, distinctId)
- markPersonlessDistinctIdInserted(team.id, distinctId)
- }
- }
-
- if (personIsMerged) {
- // The posthog_personlessdistinctid row was updated by a merge, so fetch the
- // person again (using the leader) to associate this event with the merge target.
- existingPerson = await personsStore.fetchForUpdate(team.id, distinctId)
- }
- }
+ const existingPerson = await personsStore.fetchForChecking(team.id, distinctId)
if (existingPerson) {
// A person already exists for this distinct ID, so keep the event personful.
diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts b/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts
index fbcced96ea6d..cbab1888bcaa 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts
@@ -45,9 +45,6 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(
partitionCount: options.PERSON_MERGE_EVENTS_PARTITION_COUNT,
isTeamEnabled: buildIntegerMatcher(options.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST, true),
}
- const isMergeAlwaysV1Team = buildIntegerMatcher(options.PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST, true)
- const isPersonlessWritesDisabledTeam = buildIntegerMatcher(options.PERSONLESS_WRITES_DISABLED_TEAMS, true)
-
return async function processPersonsStep(
input: TInput
): Promise<PipelineResult<TInput & ProcessPersonsOutput, AsyncOutput>> {
@@ -72,10 +69,6 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(
options.PERSON_PROPERTIES_UPDATE_ALL,
shouldUpdateLastSeenAt,
mergeEventsConfig,
- {
- mergeAlwaysV1: isMergeAlwaysV1Team(team.id),
- writesDisabled: isPersonlessWritesDisabledTeam(team.id),
- },
input.mergeFold.type === 'planned' ? input.mergeFold.plan : undefined
)
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index 46ff382e84a7..fb54846ad253 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -168,16 +168,6 @@ export type IngestionConsumerConfig = {
PERSON_MERGE_FOLD_ENABLED: boolean
// Teams eligible for merge folding: comma-separated team IDs, or '*' for all teams.
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: string
- // Always-v1 rollout of the personless-table removal RFC: for these teams, merge-added distinct
- // id mappings get version 1 unconditionally (always writing a ClickHouse override) instead of
- // consulting posthog_personlessdistinctid for the version-0 optimization. Comma-separated team
- // IDs, or '*' for all teams; empty means no teams.
- PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: string
- // Steps 3+4 of the personless-table removal RFC: for these teams, stop writing
- // posthog_personlessdistinctid (chunk inserts, single-row fallback, merge upserts) and stop
- // reading the is_merged race hint. Implies always-v1 merge versioning for the team, so the
- // table's absence can never orphan events. Comma-separated team IDs, or '*' for all teams.
- PERSONLESS_WRITES_DISABLED_TEAMS: string
// Group batch writing config
GROUP_BATCH_WRITING_USE_BATCH_UPDATES: boolean
@@ -322,8 +312,6 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '2',
PERSON_MERGE_FOLD_ENABLED: false,
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',
- PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: '',
- PERSONLESS_WRITES_DISABLED_TEAMS: '',
// Group batch writing config
GROUP_BATCH_WRITING_USE_BATCH_UPDATES: true,
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index 1fab5e16297e..ec90fe08c63a 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -291,8 +291,6 @@ export class IngestionConsumer {
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,
PERSON_MERGE_FOLD_ENABLED: this.config.PERSON_MERGE_FOLD_ENABLED,
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: this.config.PERSON_MERGE_FOLD_TEAM_ALLOWLIST,
- PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: this.config.PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST,
- PERSONLESS_WRITES_DISABLED_TEAMS: this.config.PERSONLESS_WRITES_DISABLED_TEAMS,
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,
PERSON_PROPERTIES_UPDATE_ALL: this.config.PERSON_PROPERTIES_UPDATE_ALL,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: this.config.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,
diff --git a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
index 126c453d3dc3..55ae7fb274e5 100644
--- a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
@@ -108,15 +108,9 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput & Wi
{ retry: { tries: 5, sleepMs: 100, name: 'hog_transform_event' } }
)
.pipe(createNormalizeEventStep())
- .pipe(
- createProcessPersonlessStep(
- options.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,
- options.PERSONLESS_WRITES_DISABLED_TEAMS
- ),
- {
- retry: { tries: 5, sleepMs: 100, name: 'process_personless' },
- }
- )
+ .pipe(createProcessPersonlessStep(options.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS), {
+ retry: { tries: 5, sleepMs: 100, name: 'process_personless' },
+ })
.pipe(
topHog(createProcessPersonsStep(options, outputs), [
timer('process_persons_time', (input) => ({
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index 0a08b59981b3..d501729c0b48 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -149,8 +149,6 @@ export function createJoinedIngestionPipeline<
personsPrefetchEnabled,
groupsPrefetchEnabled,
groupTypeManager,
- flagCalledPersonlessDefaultTeams: perDistinctIdOptions.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,
- personlessWritesDisabledTeams: perDistinctIdOptions.PERSONLESS_WRITES_DISABLED_TEAMS,
}
const perEventConfig: EventSubpipelineConfig = {
diff --git a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
index fcb747cc26c8..d55a827d7037 100644
--- a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
@@ -25,7 +25,6 @@ import { createDropOldEventsStep } from '~/ingestion/common/steps/event-processi
import { ChunkPipelineBuilder } from '~/ingestion/framework/builders/chunk-pipeline-builders'
import { prefetchGroupsStep } from '~/ingestion/pipelines/analytics/steps/prefetchGroupsStep'
import { prefetchPersonsStep } from '~/ingestion/pipelines/analytics/steps/prefetchPersonsStep'
-import { processPersonlessDistinctIdsChunkStep } from '~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep'
import { PluginEvent } from '~/plugin-scaffold'
import { EventHeaders, Team } from '~/types'
@@ -52,8 +51,6 @@ export interface PostTeamPreprocessingSubpipelineConfig {
personsPrefetchEnabled: boolean
groupsPrefetchEnabled: boolean
groupTypeManager: GroupTypeManager
- flagCalledPersonlessDefaultTeams: string
- personlessWritesDisabledTeams: string
}
export function createPostTeamPreprocessingSubpipeline<
@@ -79,8 +76,6 @@ export function createPostTeamPreprocessingSubpipeline<
personsPrefetchEnabled,
groupsPrefetchEnabled,
groupTypeManager,
- flagCalledPersonlessDefaultTeams,
- personlessWritesDisabledTeams,
} = config
return (
@@ -120,22 +115,5 @@ export function createPostTeamPreprocessingSubpipeline<
// Same best-effort, fire-and-forget cache warming for groups: one
// batched fetch for the chunk's $groupidentify group keys.
.pipeChunk(prefetchGroupsStep(groupTypeManager, groupsPrefetchEnabled))
- // Batch insert personless distinct IDs after prefetch (uses prefetch cache).
- // This step awaits its DB write, so retry transient persons-Postgres failures
- // (e.g. PgBouncer scale-down) instead of letting them crash the consumer loop.
- .pipeChunk(
- processPersonlessDistinctIdsChunkStep(
- personsPrefetchEnabled,
- flagCalledPersonlessDefaultTeams,
- personlessWritesDisabledTeams
- ),
- {
- retry: {
- tries: 5,
- sleepMs: 100,
- name: 'personless_distinct_ids',
- },
- }
- )
)
}
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/flag-called-personless-batching.test.ts b/nodejs/src/ingestion/pipelines/analytics/steps/flag-called-personless-batching.test.ts
deleted file mode 100644
index 23992d9212b0..000000000000
--- a/nodejs/src/ingestion/pipelines/analytics/steps/flag-called-personless-batching.test.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { DateTime } from 'luxon'
-
-import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
-import { isOkResult } from '~/ingestion/framework/results'
-import { PluginEvent } from '~/plugin-scaffold'
-import { createTestPluginEvent } from '~/tests/helpers/plugin-event'
-import { createTestTeam } from '~/tests/helpers/team'
-import { Team } from '~/types'
-
-// The chunk step (processPersonlessDistinctIdsChunkStep) and the per-event step
-// (processPersonlessStep) are coupled through the module-level LRU in
-// personless-distinct-id-cache: the chunk step pre-inserts the posthog_personlessdistinctid
-// row and marks the LRU, so the per-event step finds a hit and skips its own single-row
-// insert. Both steps are dynamically imported after resetModules so they share one fresh LRU.
-describe('flag-called personless batching: chunk step → per-event step', () => {
- let mockPersonsStore: jest.Mocked<PersonsStoreForBatch>
- let team: Team
- let processPersonlessDistinctIdsChunkStep: typeof import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep').processPersonlessDistinctIdsChunkStep
- let createProcessPersonlessStep: typeof import('~/ingestion/common/steps/event-processing/process-personless-step').createProcessPersonlessStep
-
- beforeEach(async () => {
- jest.resetModules()
- processPersonlessDistinctIdsChunkStep = (
- await import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.js')
- ).processPersonlessDistinctIdsChunkStep
- createProcessPersonlessStep = (
- await import('~/ingestion/common/steps/event-processing/process-personless-step.js')
- ).createProcessPersonlessStep
-
- team = createTestTeam()
-
- mockPersonsStore = {
- // No real person exists for the distinct ID under test.
- fetchForChecking: jest.fn().mockResolvedValue(null),
- fetchForUpdate: jest.fn().mockResolvedValue(null),
- getPersonlessBatchResult: jest.fn().mockReturnValue(undefined),
- addPersonlessDistinctId: jest.fn().mockResolvedValue(false),
- processPersonlessDistinctIdsBatch: jest.fn().mockResolvedValue(undefined),
- } as unknown as jest.Mocked<PersonsStoreForBatch>
- })
-
- const flagCalledEvent = (distinctId: string): PluginEvent =>
- createTestPluginEvent({
- distinct_id: distinctId,
- team_id: team.id,
- event: '$feature_flag_called',
- properties: {},
- uuid: `uuid-${distinctId}`,
- })
-
- const perEventInput = (event: PluginEvent) => ({
- normalizedEvent: event,
- team,
- timestamp: DateTime.utc(),
- processPerson: true,
- processPersonExplicitlyTrue: false,
- forceDisablePersonProcessing: false,
- personsStoreForBatch: mockPersonsStore,
- })
-
- it('per-event step skips its single-row insert because the batch step already inserted the row', async () => {
- const event = flagCalledEvent('user-1')
-
- // Batch step inserts the personless distinct ID and marks the shared LRU.
- await processPersonlessDistinctIdsChunkStep(
- true,
- '*'
- )([{ event, team, personsStoreForBatch: mockPersonsStore }])
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-1' },
- ])
-
- // Per-event step now sees the LRU hit and must NOT do its own single-row insert.
- const result = await createProcessPersonlessStep('*')(perEventInput(event))
-
- expect(mockPersonsStore.addPersonlessDistinctId).not.toHaveBeenCalled()
- expect(isOkResult(result)).toBe(true)
- if (isOkResult(result)) {
- // Still defaulted to personless.
- expect(result.value.processPerson).toBe(false)
- }
- })
-
- it('per-event step falls back to its single-row insert when the batch step did not run', async () => {
- const event = flagCalledEvent('user-1')
-
- // No batch step this time, so the LRU is cold.
- const result = await createProcessPersonlessStep('*')(perEventInput(event))
-
- expect(mockPersonsStore.addPersonlessDistinctId).toHaveBeenCalledTimes(1)
- expect(mockPersonsStore.addPersonlessDistinctId).toHaveBeenCalledWith(team.id, 'user-1')
- expect(isOkResult(result)).toBe(true)
- if (isOkResult(result)) {
- expect(result.value.processPerson).toBe(false)
- }
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.test.ts b/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.test.ts
deleted file mode 100644
index 1f946d83f48c..000000000000
--- a/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.test.ts
+++ /dev/null
@@ -1,295 +0,0 @@
-import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
-import { PipelineResultType } from '~/ingestion/framework/results'
-import { PluginEvent } from '~/plugin-scaffold'
-import { createTestPluginEvent } from '~/tests/helpers/plugin-event'
-import { createTestTeam } from '~/tests/helpers/team'
-import { Team } from '~/types'
-
-describe('processPersonlessDistinctIdsChunkStep', () => {
- let mockPersonsStore: jest.Mocked<PersonsStoreForBatch>
- let team: Team
- let processPersonlessDistinctIdsChunkStep: typeof import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep').processPersonlessDistinctIdsChunkStep
- let personlessDistinctIdCacheOperationsCounter: typeof import('~/ingestion/common/persons/personless-distinct-id-cache').personlessDistinctIdCacheOperationsCounter
-
- // Reads the freshly-imported counter the step writes to (resetModules gives each test its own).
- const counterValue = async (operation: string, source: string): Promise<number> => {
- const metric = await personlessDistinctIdCacheOperationsCounter.get()
- return metric.values.find((v) => v.labels.operation === operation && v.labels.source === source)?.value ?? 0
- }
-
- beforeEach(async () => {
- // Reset modules to get a fresh LRU cache for each test
- jest.resetModules()
- const module = await import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.js')
- processPersonlessDistinctIdsChunkStep = module.processPersonlessDistinctIdsChunkStep
- // Import the cache module from the same fresh graph so the counter is the one the step increments.
- personlessDistinctIdCacheOperationsCounter = (
- await import('~/ingestion/common/persons/personless-distinct-id-cache.js')
- ).personlessDistinctIdCacheOperationsCounter
-
- team = createTestTeam()
-
- mockPersonsStore = {
- processPersonlessDistinctIdsBatch: jest.fn().mockResolvedValue(undefined),
- getPersonlessBatchResult: jest.fn().mockReturnValue(undefined),
- } as unknown as jest.Mocked<PersonsStoreForBatch>
- })
-
- const createInput = (
- distinctId: string,
- processPerson: boolean | undefined = undefined,
- overrides: Partial<PluginEvent> = {},
- eventTeam: Team = team
- ): { event: PluginEvent; team: Team; personsStoreForBatch: PersonsStoreForBatch } => ({
- event: createTestPluginEvent({
- distinct_id: distinctId,
- team_id: eventTeam.id,
- properties: processPerson === undefined ? {} : { $process_person_profile: processPerson },
- uuid: `uuid-${distinctId}`,
- ...overrides,
- }),
- team: eventTeam,
- personsStoreForBatch: mockPersonsStore,
- })
-
- const createFlagCalledInput = (
- distinctId: string,
- properties: PluginEvent['properties'] = {},
- eventTeam: Team = team
- ): { event: PluginEvent; team: Team; personsStoreForBatch: PersonsStoreForBatch } =>
- createInput(distinctId, undefined, { event: '$feature_flag_called', properties }, eventTeam)
-
- describe('when enabled', () => {
- it('should process personless events and call batch insert', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true)
- const events = [createInput('user-1', false), createInput('user-2', false), createInput('user-3', false)]
-
- const results = await step(events)
-
- expect(results).toHaveLength(3)
- expect(results.every((r) => r.type === PipelineResultType.OK)).toBe(true)
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-1' },
- { teamId: team.id, distinctId: 'user-2' },
- { teamId: team.id, distinctId: 'user-3' },
- ])
- })
-
- it('should skip non-personless events', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true)
- const events = [
- createInput('user-1', true), // processPerson=true
- createInput('user-2', false), // processPerson=false (personless)
- createInput('user-3'), // processPerson=undefined (default, not personless)
- ]
-
- const results = await step(events)
-
- expect(results).toHaveLength(3)
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-2' },
- ])
- })
-
- it('should skip inserts for teams with personless writes disabled', async () => {
- const gatedTeam = createTestTeam({ id: 42 })
- const step = processPersonlessDistinctIdsChunkStep(true, '', String(gatedTeam.id))
- const events = [createInput('user-1', false, {}, gatedTeam), createInput('user-2', false)]
-
- const results = await step(events)
-
- expect(results).toHaveLength(2)
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-2' },
- ])
- })
-
- it('should not call batch insert when no personless events', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true)
- const events = [createInput('user-1', true), createInput('user-2')]
-
- const results = await step(events)
-
- expect(results).toHaveLength(2)
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
- })
-
- it('should return all events as OK even if batch insert fails', async () => {
- mockPersonsStore.processPersonlessDistinctIdsBatch.mockRejectedValue(new Error('DB error'))
-
- const step = processPersonlessDistinctIdsChunkStep(true)
- const events = [createInput('user-1', false)]
-
- // The step should throw since we don't handle errors gracefully
- await expect(step(events)).rejects.toThrow('DB error')
- })
- })
-
- describe('when disabled', () => {
- it('should not process any events', async () => {
- const step = processPersonlessDistinctIdsChunkStep(false)
- const events = [createInput('user-1', false), createInput('user-2', false)]
-
- const results = await step(events)
-
- expect(results).toHaveLength(2)
- expect(results.every((r) => r.type === PipelineResultType.OK)).toBe(true)
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
- })
- })
-
- describe('LRU cache behavior', () => {
- it('should deduplicate entries within same batch before hitting cache', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true)
- const events = [
- createInput('user-1', false),
- createInput('user-1', false), // Duplicate - deduped before cache/insert
- createInput('user-2', false),
- ]
-
- await step(events)
-
- // Duplicates are removed before batch insert
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-1' },
- { teamId: team.id, distinctId: 'user-2' },
- ])
- })
-
- it('should use cache to skip already-inserted distinct IDs across batches', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true)
-
- // First batch
- await step([createInput('user-1', false)])
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-1' },
- ])
-
- mockPersonsStore.processPersonlessDistinctIdsBatch.mockClear()
-
- // Second batch - user-1 should be cached, only user-2 should be inserted
- await step([createInput('user-1', false), createInput('user-2', false)])
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-2' },
- ])
- })
- })
-
- describe('$feature_flag_called batching', () => {
- it('should batch insert flag-called candidates for enabled teams', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true, String(team.id))
- const events = [createFlagCalledInput('user-1'), createFlagCalledInput('user-2')]
-
- await step(events)
-
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-1' },
- { teamId: team.id, distinctId: 'user-2' },
- ])
- })
-
- it('should not insert flag-called events when the team is not enabled', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true, '') // no enabled teams
- const events = [createFlagCalledInput('user-1')]
-
- await step(events)
-
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
- })
-
- it('should only insert flag-called candidates from teams in the matcher, not others in the same batch', async () => {
- const otherTeam = createTestTeam({ id: team.id + 1 })
- const step = processPersonlessDistinctIdsChunkStep(true, String(team.id)) // only `team` enabled
-
- const events = [
- createFlagCalledInput('enabled-user'),
- createFlagCalledInput('other-team-user', {}, otherTeam),
- ]
-
- const results = await step(events)
-
- expect(results).toHaveLength(2)
- expect(results.every((r) => r.type === PipelineResultType.OK)).toBe(true)
- // Only the enabled team's distinct ID is inserted; the other team's flag-called event is skipped.
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'enabled-user' },
- ])
- })
-
- it('should support "*" to enable flag-called batching for all teams', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true, '*')
- const events = [createFlagCalledInput('user-1')]
-
- await step(events)
-
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-1' },
- ])
- })
-
- it('should skip flag-called events that explicitly set $process_person_profile=true', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true, '*')
- const events = [createFlagCalledInput('user-1', { $process_person_profile: true })]
-
- await step(events)
-
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
- })
-
- it('should skip flag-called events carrying group keys', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true, '*')
- const events = [createFlagCalledInput('user-1', { $groups: { org: 'acme' } })]
-
- await step(events)
-
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
- })
-
- it('should treat a flag-called event with $process_person_profile=false as explicit-personless', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true, '') // flag-called batching off
- const events = [createFlagCalledInput('user-1', { $process_person_profile: false })]
-
- await step(events)
-
- // Still inserted via the explicit-personless branch, independent of flag-called enablement.
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-1' },
- ])
- })
-
- it('should batch explicit-personless and flag-called candidates together', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true, '*')
- const events = [createInput('user-1', false), createFlagCalledInput('user-2')]
-
- await step(events)
-
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).toHaveBeenCalledWith([
- { teamId: team.id, distinctId: 'user-1' },
- { teamId: team.id, distinctId: 'user-2' },
- ])
- })
-
- it('should not insert flag-called candidates when disabled', async () => {
- const step = processPersonlessDistinctIdsChunkStep(false, '*')
- const events = [createFlagCalledInput('user-1')]
-
- await step(events)
-
- expect(mockPersonsStore.processPersonlessDistinctIdsBatch).not.toHaveBeenCalled()
- })
-
- it('should count hits and misses per source on the cache counter', async () => {
- const step = processPersonlessDistinctIdsChunkStep(true, '*')
-
- // First batch: one flag-called and one explicit-personless distinct ID, both cold -> one miss each.
- await step([createFlagCalledInput('ff-1'), createInput('batch-1', false)])
- // Second batch: ff-1 is warm in the LRU now -> one flag_called hit, no new insert.
- await step([createFlagCalledInput('ff-1')])
-
- expect(await counterValue('miss', 'flag_called')).toBe(1)
- expect(await counterValue('miss', 'batch')).toBe(1)
- expect(await counterValue('hit', 'flag_called')).toBe(1)
- expect(await counterValue('hit', 'batch')).toBe(0)
- })
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.ts b/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.ts
deleted file mode 100644
index 7737b250b065..000000000000
--- a/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-import { buildIntegerMatcher } from '~/common/config/config'
-import {
- buildFlagCalledPersonlessMatcher,
- isFlagCalledPersonlessCandidate,
-} from '~/ingestion/common/persons/flag-called-personless'
-import {
- hasInsertedPersonlessDistinctId,
- markPersonlessDistinctIdInserted,
- personlessDistinctIdCacheOperationsCounter,
-} from '~/ingestion/common/persons/personless-distinct-id-cache'
-import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
-import { DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS } from '~/ingestion/config'
-import { PipelineResult, ok } from '~/ingestion/framework/results'
-import { PipelineEvent, Team } from '~/types'
-
-type ProcessPersonlessDistinctIdsChunkStepInput = {
- event: PipelineEvent
- team: Team
- personsStoreForBatch: PersonsStoreForBatch
-}
-
-type PersonlessSource = 'batch' | 'flag_called'
-
-/**
- * Chunk step that inserts personless distinct IDs into posthog_personlessdistinctid. This
- * runs after prefetchPersonsStep (which fires off person-existence fetches in the background)
- * and before the per-event processPersonlessStep, which awaits those fetches via fetchForChecking
- * and reads the is_merged results stored here.
- *
- * Two kinds of events are inserted, both via the same UNNEST batch insert:
- * - "batch": events explicitly marked personless ($process_person_profile === false).
- * - "flag_called": $feature_flag_called events that default to personless for enabled teams
- * (see #60581). Batching these here avoids one single-row insert per first-seen distinct
- * ID in processPersonlessStep, which contends on the table's incrementing-integer PK at
- * high volume. The per-event step still makes the final personless/personful decision; it
- * just finds the row already inserted (LRU hit) and skips its own insert. The single-row
- * insert remains the fallback when this step is disabled.
- *
- * Inserting a row for a flag_called distinct ID that turns out to have a real person is
- * harmless: the explicit-personless path already inserts unconditionally, every reader is
- * gated on the absence of a real person, and coexistence is the normal post-merge state. So
- * this step does not need a per-row person check.
- */
-export function processPersonlessDistinctIdsChunkStep<T extends ProcessPersonlessDistinctIdsChunkStepInput>(
- enabled: boolean,
- flagCalledPersonlessDefaultTeams: string = DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,
- personlessWritesDisabledTeams: string = ''
-) {
- const flagCalledDefaultEnabledForTeam = buildFlagCalledPersonlessMatcher(flagCalledPersonlessDefaultTeams)
- const writesDisabledForTeam = buildIntegerMatcher(personlessWritesDisabledTeams, true)
-
- return async function processPersonlessDistinctIdsChunkStep(events: T[]): Promise<PipelineResult<T>[]> {
- if (enabled) {
- // Events in a chunk may come from different Kafka batches (due to the feed primitive).
- // Group by personsStoreForBatch so each batch's is_merged results land in the right
- // cache. Deduplicate per batch to avoid redundant DB calls within the same batch.
- type StoreData = { seenInBatch: Set<string>; entries: { teamId: number; distinctId: string }[] }
- const entriesByStore = new Map<PersonsStoreForBatch, StoreData>()
- const cacheHits: Record<PersonlessSource, number> = { batch: 0, flag_called: 0 }
- const cacheMisses: Record<PersonlessSource, number> = { batch: 0, flag_called: 0 }
-
- for (const e of events) {
- // Personless-table writes are disabled for this team (stop-writing rollout);
- // the event still goes personless, just without the bookkeeping row.
- if (writesDisabledForTeam(e.team.id)) {
- continue
- }
- const source = personlessSource(e, flagCalledDefaultEnabledForTeam)
- if (source === null) {
- continue
- }
- const cacheKey = `${e.team.id}|${e.event.distinct_id}`
-
- let storeData = entriesByStore.get(e.personsStoreForBatch)
- if (!storeData) {
- storeData = { seenInBatch: new Set(), entries: [] }
- entriesByStore.set(e.personsStoreForBatch, storeData)
- }
-
- if (storeData.seenInBatch.has(cacheKey)) {
- continue
- }
- storeData.seenInBatch.add(cacheKey)
-
- if (hasInsertedPersonlessDistinctId(e.team.id, e.event.distinct_id)) {
- cacheHits[source]++
- } else {
- cacheMisses[source]++
- storeData.entries.push({ teamId: e.team.id, distinctId: e.event.distinct_id })
- }
- }
-
- for (const source of ['batch', 'flag_called'] as const) {
- if (cacheHits[source] > 0) {
- personlessDistinctIdCacheOperationsCounter.inc({ operation: 'hit', source }, cacheHits[source])
- }
- if (cacheMisses[source] > 0) {
- personlessDistinctIdCacheOperationsCounter.inc({ operation: 'miss', source }, cacheMisses[source])
- }
- }
-
- const storeCalls = Array.from(entriesByStore.entries()).filter(([, { entries }]) => entries.length > 0)
-
- if (storeCalls.length > 0) {
- await Promise.all(
- storeCalls.map(async ([store, { entries }]) => {
- await store.processPersonlessDistinctIdsBatch(entries)
- for (const entry of entries) {
- markPersonlessDistinctIdInserted(entry.teamId, entry.distinctId)
- }
- })
- )
- }
- }
- return events.map((event) => ok(event))
- }
-}
-
-function personlessSource(
- e: ProcessPersonlessDistinctIdsChunkStepInput,
- flagCalledDefaultEnabledForTeam: (teamId: number) => boolean
-): PersonlessSource | null {
- const processPersonProfile = e.event.properties?.$process_person_profile
- if (processPersonProfile === false) {
- return 'batch'
- }
- // The per-event step uses the captured processPersonExplicitlyTrue; this step runs before
- // normalizeProcessPerson strips the property, so reading it from the raw event is valid.
- const processPersonExplicitlyTrue = processPersonProfile === true
- if (
- isFlagCalledPersonlessCandidate(
- e.event,
- e.team.id,
- processPersonExplicitlyTrue,
- flagCalledDefaultEnabledForTeam
- )
- ) {
- return 'flag_called'
- }
- return null
-}
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
index 1947777f9f97..e119bcfc78d6 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts
@@ -241,9 +241,6 @@ describe('ErrorTrackingPipeline', () => {
updatePersonsBatch: jest.fn(),
deletePerson: jest.fn(),
addDistinctId: jest.fn(),
- addPersonlessDistinctId: jest.fn(),
- addPersonlessDistinctIdForMerge: jest.fn(),
- addPersonlessDistinctIdsBatch: jest.fn(),
personPropertiesSize: jest.fn(),
updateCohortsAndFeatureFlagsForMerge: jest.fn(),
inTransaction: jest.fn(),
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index a38fd232409b..6d2a0fe4958c 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -398,8 +398,6 @@ export class IngestionApiServer implements NodeServer {
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,
PERSON_MERGE_FOLD_ENABLED: this.config.PERSON_MERGE_FOLD_ENABLED,
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: this.config.PERSON_MERGE_FOLD_TEAM_ALLOWLIST,
- PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: this.config.PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST,
- PERSONLESS_WRITES_DISABLED_TEAMS: this.config.PERSONLESS_WRITES_DISABLED_TEAMS,
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,
PERSON_PROPERTIES_UPDATE_ALL: this.config.PERSON_PROPERTIES_UPDATE_ALL,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: this.config.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,
diff --git a/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts b/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts
index f0b80ca7152d..0a8700a90715 100644
--- a/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts
+++ b/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts
@@ -54,8 +54,6 @@ describe('createProcessPersonsStep', () => {
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '*',
PERSON_MERGE_FOLD_ENABLED: false,
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',
- PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: '',
- PERSONLESS_WRITES_DISABLED_TEAMS: '',
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,
PERSON_PROPERTIES_UPDATE_ALL: false,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',
@@ -419,7 +417,7 @@ describe('createProcessPersonsStep', () => {
}
})
- describe('personless-table removal rollout gates', () => {
+ describe('merge distinct id versioning', () => {
function identify(anonDistinctId: string, targetDistinctId: string): PluginEvent {
return {
...pluginEvent,
@@ -430,8 +428,8 @@ describe('createProcessPersonsStep', () => {
}
}
- async function runIdentify(event: PluginEvent, overrides: Partial<EventPipelineRunnerOptions>): Promise<void> {
- const step = createProcessPersonsStep({ ...options, ...overrides }, personOutputs)
+ async function runIdentify(event: PluginEvent): Promise<void> {
+ const step = createProcessPersonsStep(options, personOutputs)
const result = await step(
createInput({ normalizedEvent: event, timestamp: DateTime.fromISO(event.timestamp!) })
)
@@ -449,47 +447,28 @@ describe('createProcessPersonsStep', () => {
return Number(result.rows[0].version ?? 0)
}
- it('writes version 1 for merge-added distinct ids only for allowlisted teams', async () => {
+ it('writes version 1 for a merge-added distinct id and no personless bookkeeping row', async () => {
await createPersonWithDistinctIds('user-1')
- // Neither anon id has personless history, so without the gate both would get version 0.
- await runIdentify(identify('anon-gated', 'user-1'), {
- PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: `${teamId}`,
- })
- await runIdentify(identify('anon-ungated', 'user-1'), {
- PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: `${teamId + 1}`,
- })
+ await runIdentify(identify('anon-1', 'user-1'))
- expect(await versionOf('anon-gated')).toBe(1)
- expect(await versionOf('anon-ungated')).toBe(0)
+ expect(await versionOf('anon-1')).toBe(1)
+ const personlessRows = await infra.postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT 1 FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2',
+ [teamId, 'anon-1'],
+ 'fetchPersonlessRow'
+ )
+ expect(personlessRows.rows).toHaveLength(0)
})
it('gives the non-primary distinct id version 1 when neither points at a person', async () => {
- await runIdentify(identify('anon-new', 'user-new'), { PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: '*' })
+ await runIdentify(identify('anon-new', 'user-new'))
// The event distinct id derives the person uuid, so it stays at version 0.
expect(await versionOf('user-new')).toBe(0)
expect(await versionOf('anon-new')).toBe(1)
})
-
- it('skips personless bookkeeping but still writes version 1 when writes are disabled', async () => {
- await createPersonWithDistinctIds('user-2')
-
- // The always-v1 allowlist is empty: writes-disabled alone must force version 1,
- // since without the bookkeeping row a table consult would pick version 0.
- await runIdentify(identify('anon-nowrites', 'user-2'), {
- PERSONLESS_WRITES_DISABLED_TEAMS: `${teamId}`,
- })
-
- expect(await versionOf('anon-nowrites')).toBe(1)
- const personlessRows = await infra.postgres.query(
- PostgresUse.PERSONS_WRITE,
- 'SELECT 1 FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2',
- [teamId, 'anon-nowrites'],
- 'fetchPersonlessRow'
- )
- expect(personlessRows.rows).toHaveLength(0)
- })
})
describe('merge folding', () => {
@@ -665,15 +644,11 @@ describe('createProcessPersonsStep', () => {
expect(distinctIds.sort()).toEqual(['anon-1', 'anon-2', 'user-1'])
})
- it('folded personless adds get version 1 for always-v1 teams', async () => {
+ it('folded adds for distinct ids without a person get version 1', async () => {
await createPersonWithProps('anon-1', { a: 1 })
- // anon-2 has no person row and no personless history, so without the gate it would get version 0
const plan = planFor('user-1', 'anon-1', 'anon-2')
- await runIdentifies([identifyEvent('anon-1', 'user-1')], plan, {
- ...foldOptions,
- PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: '*',
- })
+ await runIdentifies([identifyEvent('anon-1', 'user-1')], plan, foldOptions)
expect(plan.status).toBe('executed')
const rows = await fetchDistinctIds(infra.postgres, plan.mergedPerson!)
diff --git a/nodejs/tests/ingestion/person-state-batch.test.ts b/nodejs/tests/ingestion/person-state-batch.test.ts
index db2ba238b4ea..d1fab31c3797 100644
--- a/nodejs/tests/ingestion/person-state-batch.test.ts
+++ b/nodejs/tests/ingestion/person-state-batch.test.ts
@@ -342,11 +342,6 @@ describe('PersonState.processEvent()', () => {
return await clickhouse.query<ClickHousePerson>(query)
}
- async function fetchOverridesForDistinctId(distinctId: string) {
- const query = `SELECT * FROM person_distinct_id_overrides_mv FINAL WHERE team_id = ${teamId} AND distinct_id = '${distinctId}'`
- return await clickhouse.query(query)
- }
-
async function fetchPersonsRowsWithVersionHigerEqualThan(version = 1) {
const query = `SELECT * FROM person FINAL WHERE team_id = ${teamId} AND version >= ${version}`
return await clickhouse.query(query)
@@ -407,73 +402,6 @@ describe('PersonState.processEvent()', () => {
expect(personPrimaryTeam.uuid).not.toEqual(personOtherTeam.uuid)
})
- it('overrides are created only when distinct_id is in posthog_personlessdistinctid', async () => {
- // oldUserDistinctId exists, and 'old2' will merge into it, but not create an override
- await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, oldUserUuid, {
- distinctId: oldUserDistinctId,
- })
-
- // newUserDistinctId exists, and 'new2' will merge into it, and will create an override
- await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, newUserUuid, {
- distinctId: newUserDistinctId,
- })
-
- const personRepository = new PostgresPersonRepository(hub.postgres)
- await personRepository.addPersonlessDistinctId(teamId, 'new2')
-
- const hubParam = undefined
- const processPerson = true
- const result1 = await personProcessor(
- {
- event: '$identify',
- distinct_id: oldUserDistinctId,
- properties: {
- $anon_distinct_id: 'old2',
- },
- },
- undefined,
- undefined,
- hubParam,
- processPerson
- ).processEvent()
-
- const result2 = await personProcessor(
- {
- event: '$identify',
- distinct_id: newUserDistinctId,
- properties: {
- $anon_distinct_id: 'new2',
- },
- },
- undefined,
- undefined,
- hubParam,
- processPerson
- ).processEvent()
-
- await kafkaProducer.flush()
- await Promise.all(result1.sideEffects)
- await Promise.all(result2.sideEffects)
-
- // new2 has an override, because it was in posthog_personlessdistinctid
- await clickhouse.delayUntilEventIngested(() => fetchOverridesForDistinctId('new2'))
- const chOverrides = await fetchOverridesForDistinctId('new2')
- expect(chOverrides.length).toEqual(1)
- expect(chOverrides).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- distinct_id: 'new2',
- person_id: newUserUuid,
- version: 1,
- }),
- ])
- )
-
- // old2 has no override, because it wasn't in posthog_personlessdistinctid
- const chOverridesOld = await fetchOverridesForDistinctId('old2')
- expect(chOverridesOld.length).toEqual(0)
- })
-
it('creates person if they are new', async () => {
const event_uuid = new UUIDT().toString()
const [person, kafkaAcks] = await personPropertyService({