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.

perf(nodejs): move eleven serial test suites to the parallel lane (#89152)

Ben White3e5483137f64
diff --git a/nodejs/src/cdp/_tests/fixtures.ts b/nodejs/src/cdp/_tests/fixtures.ts
index 30664204a379..2d3876221a47 100644
--- a/nodejs/src/cdp/_tests/fixtures.ts
+++ b/nodejs/src/cdp/_tests/fixtures.ts
@@ -4,7 +4,7 @@ import { Message } from 'node-rdkafka'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { UUIDT } from '~/common/utils/utils'
-import { getTeamMemberUserId, insertRow } from '~/tests/helpers/sql'
+import { getTeamMemberUserId, insertRow, uniqueTestId } from '~/tests/helpers/sql'
import { ClickHousePerson, ClickHouseTimestamp, ProjectId, RawClickHouseEvent, Team } from '../../types'
import { CohortMembershipChange } from '../consumers/cdp-cohort-membership.consumer'
@@ -58,7 +58,7 @@ export const createHogFunction = (hogFunction: Partial<HogFunctionType>) => {
export const createIntegration = (integration: Partial<IntegrationType>) => {
const item: IntegrationType = {
team_id: 1,
- id: integration.id ?? 1,
+ id: integration.id ?? uniqueTestId(),
kind: integration.kind ?? 'slack',
config: {},
sensitive_config: {},
@@ -184,27 +184,33 @@ export const insertHogFunctionTemplate = async (
template.bytecode = await compileHog(template.code)
}
- const res = await insertRow(postgres, 'posthog_hogfunctiontemplate', {
- id: randomUUID(),
- template_id: template.id,
- sha: 'sha',
- name: template.name,
- description: template.description,
- code: template.code,
- code_language: template.code_language,
- status: template.status,
- free: template.free,
- category: template.category,
- icon_url: template.icon_url,
- filters: template.filters,
- masking: template.masking,
- mappings: template.mappings,
- bytecode: template.bytecode,
- inputs_schema: template.inputs_schema,
- type: template.type,
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- })
+ const res = await insertRow(
+ postgres,
+ 'posthog_hogfunctiontemplate',
+ {
+ id: randomUUID(),
+ template_id: template.id,
+ sha: 'sha',
+ name: template.name,
+ description: template.description,
+ code: template.code,
+ code_language: template.code_language,
+ status: template.status,
+ free: template.free,
+ category: template.category,
+ icon_url: template.icon_url,
+ filters: template.filters,
+ masking: template.masking,
+ mappings: template.mappings,
+ bytecode: template.bytecode,
+ inputs_schema: template.inputs_schema,
+ type: template.type,
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ },
+ // Templates are global, so a suite that no longer wipes the database re-inserts its own.
+ `ON CONFLICT (template_id, sha) DO UPDATE SET updated_at = EXCLUDED.updated_at`
+ )
return res
}
diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.serial.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
similarity index 98%
rename from nodejs/src/cdp/rerun/rerun-paginator.service.serial.test.ts
rename to nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
index 0491c7d5b8a3..3a794c4634ba 100644
--- a/nodejs/src/cdp/rerun/rerun-paginator.service.serial.test.ts
+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts
@@ -1,4 +1,3 @@
-// Serial: truncates shared ClickHouse lifecycle data and uses a shared Kafka-to-ClickHouse materialized view.
import { MockKafkaProducerWrapper } from '~/tests/helpers/mocks/producer.mock'
import { ClickHouseClient } from '@clickhouse/client'
@@ -13,7 +12,7 @@ import { Clickhouse } from '~/tests/helpers/clickhouse'
import { waitForExpect } from '~/tests/helpers/expectations'
import { waitForHogInvocationResultsMvReady } from '~/tests/helpers/hog-invocation-results'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
-import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
+import { createTestTeamFixture } from '~/tests/helpers/sql'
import { Hub, Team } from '../../types'
import { insertHogFunction as _insertHogFunction, createHogExecutionGlobals } from '../_tests/fixtures'
@@ -194,18 +193,15 @@ describe('RerunPaginatorService integration', () => {
// consumers keep their connections. Includes KAFKA_HOG_INVOCATION_RESULTS, which this test's
// MV needs but the shared set does not cover.
await ensureKafkaTopics([...TEST_KAFKA_TOPICS, KAFKA_HOG_INVOCATION_RESULTS])
- await clickhouse.truncate('hog_invocation_results_data')
await waitForHogInvocationResultsMvReady(clickhouse)
})
beforeEach(async () => {
- await resetTestDatabase()
- await clickhouse.truncate('hog_invocation_results_data')
seededCount = 0
hub = await createHub()
kafkaProducer = await ActualKafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)
- team = await getFirstTeam(hub.postgres)
+ team = (await createTestTeamFixture(hub.postgres)).team
// Real seeding path: outputs → kafka → MV → CH.
const deps = createCdpConsumerDeps(hub, kafkaProducer)
diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
index 1d8553f13e44..4b14cdb61023 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -106,6 +106,16 @@ async function queryJob(id: string): Promise<RawJobRow> {
return res.rows[0]
}
+// Compares in the database: `scheduled` and Date.now() are different clocks and skew.
+async function jobIsDue(id: string): Promise<boolean> {
+ const res = await assertPool.query<{ due: boolean }>(
+ 'SELECT scheduled <= now() AS due FROM cyclotron_jobs WHERE id = $1',
+ [id]
+ )
+ expect(res.rows).toHaveLength(1)
+ return res.rows[0].due
+}
+
async function countByStatus(status: string): Promise<number> {
const res = await assertPool.query('SELECT COUNT(*)::int AS c FROM cyclotron_jobs WHERE status = $1', [status])
return res.rows[0].c
@@ -790,13 +800,13 @@ describe('Cyclotron V2', () => {
// instead of after the remaining (potentially days-long) delay.
const parked = await queryJob(parkedId)
expect(parked.cancel_requested_at).not.toBeNull()
- expect(new Date(parked.scheduled).getTime()).toBeLessThanOrEqual(Date.now())
+ expect(await jobIsDue(parkedId)).toBe(true)
// Running row: flagged only. Its wake is pulled forward by the
// worker's release, never by an external write racing the lock.
const running = await queryJob(runningId)
expect(running.cancel_requested_at).not.toBeNull()
- expect(new Date(running.scheduled).getTime()).toBeGreaterThan(Date.now())
+ expect(await jobIsDue(runningId)).toBe(false)
// Terminal row: untouched, so a later rerun doesn't inherit a flag.
const completed = await queryJob(completedId)
@@ -847,7 +857,7 @@ describe('Cyclotron V2', () => {
// flagged in place, its wake pulled forward by the worker's release.
const resolver = await queryJob(resolverId)
expect(resolver.cancel_requested_at).not.toBeNull()
- expect(new Date(resolver.scheduled).getTime()).toBeLessThanOrEqual(Date.now())
+ expect(await jobIsDue(resolverId)).toBe(true)
expect((await queryJob(parkedChildId)).cancel_requested_at).not.toBeNull()
expect((await queryJob(runningChildId)).cancel_requested_at).not.toBeNull()
expect((await queryJob(otherRunId)).cancel_requested_at).toBeNull()
@@ -913,7 +923,7 @@ describe('Cyclotron V2', () => {
const row = await queryJob(id)
expect(row.status).toBe('available')
- expect(new Date(row.scheduled).getTime()).toBeLessThanOrEqual(Date.now())
+ expect(await jobIsDue(id)).toBe(true)
})
it('dequeued jobs expose cancelRequestedAt so consumers can terminate instead of executing', async () => {
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.serial.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
similarity index 99%
rename from nodejs/src/cdp/services/hogflows/hogflow-executor.service.serial.test.ts
rename to nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
index ada155c6c325..5a25a6118638 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.serial.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -1,4 +1,3 @@
-// Serial: resets shared Postgres and relies on the reset-created default team.
// sort-imports-ignore
import { DateTime, Duration } from 'luxon'
@@ -10,9 +9,9 @@ import { compileHog } from '~/cdp/templates/compiler'
import { createHub } from '~/common/utils/db/hub'
import { logger } from '~/common/utils/logger'
import { fetch } from '~/common/utils/request'
-import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
+import { createTestTeamFixture, uniqueTestId } from '~/tests/helpers/sql'
-import { Hub } from '../../../types'
+import { Hub, Team } from '../../../types'
import { HOG_FILTERS_EXAMPLES } from '../../_tests/examples'
import { createExampleHogFlowInvocation } from '../../_tests/fixtures-hogflows'
import { CohortMembershipRepository } from '../cohorts/cohort-membership-repository'
@@ -50,6 +49,8 @@ const cleanLogs = (logs: string[]): string[] => {
describe('Hogflow Executor', () => {
let executor: HogFlowExecutorService
let hub: Hub
+ let team: Team
+ let integrationId: number
const mockFetch = jest.mocked(fetch)
beforeEach(async () => {
@@ -63,10 +64,11 @@ describe('Hogflow Executor', () => {
}
})
- await resetTestDatabase()
hub = await createHub({
SITE_URL: 'http://localhost:8000',
})
+ team = (await createTestTeamFixture(hub.postgres)).team
+ integrationId = uniqueTestId()
const hogInputsService = new HogInputsService(
hub.integrationManager,
new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL),
@@ -2619,10 +2621,8 @@ describe('Hogflow Executor', () => {
}
it('should record billing metrics for both regular hog functions and email functions', async () => {
- const team = await getFirstTeam(hub.postgres)
-
await insertIntegration(hub.postgres, team.id, {
- id: 1,
+ id: integrationId,
kind: 'email',
config: {
@@ -2696,7 +2696,7 @@ describe('Hogflow Executor', () => {
name: 'Recipient',
},
from: {
- integrationId: 1,
+ integrationId,
},
subject: 'Test Email 1',
text: 'Test Text 1',
@@ -2718,7 +2718,7 @@ describe('Hogflow Executor', () => {
name: 'Recipient 2',
},
from: {
- integrationId: 1,
+ integrationId,
},
subject: 'Test Email 2',
text: 'Test Text 2',
@@ -2775,10 +2775,8 @@ describe('Hogflow Executor', () => {
describe('email queue routing', () => {
it('should route email actions to the email queue', async () => {
- const team = await getFirstTeam(hub.postgres)
-
await insertIntegration(hub.postgres, team.id, {
- id: 1,
+ id: integrationId,
kind: 'email',
config: {
@@ -2834,7 +2832,7 @@ describe('Hogflow Executor', () => {
email: {
value: {
to: { email: '[email protected]', name: 'Recipient' },
- from: { integrationId: 1, email: '[email protected]' },
+ from: { integrationId, email: '[email protected]' },
subject: 'Test Email',
text: 'Test',
html: '<p>Test</p>',
@@ -2869,10 +2867,8 @@ describe('Hogflow Executor', () => {
})
it('should complete the full round-trip: hogflow → email queue → email sent → workflow continues', async () => {
- const team = await getFirstTeam(hub.postgres)
-
await insertIntegration(hub.postgres, team.id, {
- id: 1,
+ id: integrationId,
kind: 'email',
config: {
@@ -2928,7 +2924,7 @@ describe('Hogflow Executor', () => {
email: {
value: {
to: { email: '[email protected]', name: 'Recipient' },
- from: { integrationId: 1, email: '[email protected]' },
+ from: { integrationId, email: '[email protected]' },
subject: 'Test Email',
text: 'Test text',
html: '<p>Test html</p>',
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts
index 1d4746418e2f..88d0a22ecf22 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts
@@ -75,13 +75,17 @@ describe('HogFlowManager', () => {
expect(items.map((item) => item.team_id)).toEqual([teamId1, teamId1])
expect(
- forSnapshot(items, {
- overrides: {
- team_id: 'TEAM_ID',
- created_at: 'CREATED_AT',
- updated_at: 'UPDATED_AT',
- },
- })
+ // The manager's queries are unordered, so sort before snapshotting.
+ forSnapshot(
+ [...items].sort((a, b) => a.name.localeCompare(b.name)),
+ {
+ overrides: {
+ team_id: 'TEAM_ID',
+ created_at: 'CREATED_AT',
+ updated_at: 'UPDATED_AT',
+ },
+ }
+ )
).toMatchSnapshot()
await hub.postgres.query(
diff --git a/nodejs/src/cdp/services/legacy-plugin-executor.service.test.ts b/nodejs/src/cdp/services/legacy-plugin-executor.service.test.ts
index 9c04c4b8f072..8a9fdbbb2f4b 100644
--- a/nodejs/src/cdp/services/legacy-plugin-executor.service.test.ts
+++ b/nodejs/src/cdp/services/legacy-plugin-executor.service.test.ts
@@ -5,7 +5,7 @@ import { DateTime } from 'luxon'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { PostgresUse } from '~/common/utils/db/postgres'
import { forSnapshot } from '~/tests/helpers/snapshots'
-import { createTestTeamFixture } from '~/tests/helpers/sql'
+import { createTestTeamFixture, uniqueTestId } from '~/tests/helpers/sql'
import { Hub, Team } from '../../types'
import { createExampleInvocation, createHogExecutionGlobals, createHogFunction } from '../_tests/fixtures'
@@ -54,8 +54,7 @@ describe('LegacyPluginExecutorService', () => {
const fixedTime = DateTime.fromObject({ year: 2025, month: 1, day: 1 }, { zone: 'UTC' })
jest.spyOn(Date, 'now').mockReturnValue(fixedTime.toMillis())
- // Generate a unique plugin ID to avoid conflicts
- uniquePluginId = 50000 + Math.floor(Math.random() * 100000)
+ uniquePluginId = uniqueTestId()
// Create a plugin in the database
await hub.postgres.query(
diff --git a/nodejs/src/common/groups/repositories/postgres-group-repository.integration.serial.test.ts b/nodejs/src/common/groups/repositories/postgres-group-repository.integration.test.ts
similarity index 98%
rename from nodejs/src/common/groups/repositories/postgres-group-repository.integration.serial.test.ts
rename to nodejs/src/common/groups/repositories/postgres-group-repository.integration.test.ts
index cd9d721bb185..560bdf09ce05 100644
--- a/nodejs/src/common/groups/repositories/postgres-group-repository.integration.serial.test.ts
+++ b/nodejs/src/common/groups/repositories/postgres-group-repository.integration.test.ts
@@ -1,10 +1,9 @@
-// Serial: resets shared Postgres and Redis while fixtures use fixed team, project, and organization IDs.
import { DateTime } from 'luxon'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'
import { UUIDT } from '~/common/utils/utils'
-import { insertRow, resetTestDatabase } from '~/tests/helpers/sql'
+import { createOrganization, insertRow, uniqueTestId } from '~/tests/helpers/sql'
import {
GroupTypeIndex,
Hub,
@@ -24,22 +23,21 @@ describe('PostgresGroupRepository Integration', () => {
let repository: PostgresGroupRepository
let postgres: PostgresRouter
+ let organizationId: string
+ let teamId: TeamId
+
beforeEach(async () => {
hub = await createHub()
- await resetTestDatabase()
postgres = hub.postgres
repository = new PostgresGroupRepository(postgres)
-
- const redis = await hub.redisPool.acquire()
- await redis.flushdb()
- await hub.redisPool.release(redis)
+ organizationId = await createOrganization(postgres)
+ teamId = uniqueTestId() as TeamId
})
afterEach(async () => {
await closeHub(hub)
})
- const teamId = 1 as TeamId
const groupTypeIndex = 0 as GroupTypeIndex
const groupKey = 'test-group-key'
const groupProperties = { name: 'Test Group', type: 'company' }
@@ -51,7 +49,7 @@ describe('PostgresGroupRepository Integration', () => {
// First create the project that the team references
await insertRow(postgres, 'posthog_project', {
id: teamId,
- organization_id: 'ca30f2ec-e9a4-4001-bf27-3ef194086068',
+ organization_id: organizationId,
name: `Test Project ${teamId}`,
created_at: new Date().toISOString(),
})
@@ -60,7 +58,7 @@ describe('PostgresGroupRepository Integration', () => {
await insertRow(postgres, 'posthog_team', {
id: teamId,
name: `Test Team ${teamId}`,
- organization_id: 'ca30f2ec-e9a4-4001-bf27-3ef194086068',
+ organization_id: organizationId,
project_id: teamId,
uuid: new UUIDT().toString(),
api_token: `test-api-token-${teamId}`,
@@ -195,29 +193,29 @@ describe('PostgresGroupRepository Integration', () => {
it('should handle different group types and keys', async () => {
const group1Key = 'company-group-1'
const group1TypeIndex = 0 as GroupTypeIndex
- const group1TeamId = 10 as TeamId
- const group1ProjectId = 101
+ const group1TeamId = uniqueTestId() as TeamId
+ const group1ProjectId = uniqueTestId()
const group1Properties = { name: 'Company A', industry: 'tech' }
const group1CreatedAt = DateTime.fromISO('2023-01-01T00:00:00Z').toUTC()
const group2Key = 'organization-group-2'
const group2TypeIndex = 1 as GroupTypeIndex
- const group2TeamId = 20 as TeamId
- const group2ProjectId = 102
+ const group2TeamId = uniqueTestId() as TeamId
+ const group2ProjectId = uniqueTestId()
const group2Properties = { name: 'Organization B', sector: 'finance' }
const group2CreatedAt = DateTime.fromISO('2023-02-01T00:00:00Z').toUTC()
// Insert first group with its own team/project
await insertRow(postgres, 'posthog_project', {
id: group1ProjectId,
- organization_id: 'ca30f2ec-e9a4-4001-bf27-3ef194086068',
+ organization_id: organizationId,
name: `Test Project ${group1ProjectId}`,
created_at: new Date().toISOString(),
})
await insertRow(postgres, 'posthog_team', {
id: group1TeamId,
name: `Test Team ${group1TeamId}`,
- organization_id: 'ca30f2ec-e9a4-4001-bf27-3ef194086068',
+ organization_id: organizationId,
project_id: group1ProjectId,
uuid: new UUIDT().toString(),
api_token: `test-api-token-${group1TeamId}`,
@@ -258,14 +256,14 @@ describe('PostgresGroupRepository Integration', () => {
// Insert second group with its own team/project
await insertRow(postgres, 'posthog_project', {
id: group2ProjectId,
- organization_id: 'ca30f2ec-e9a4-4001-bf27-3ef194086068',
+ organization_id: organizationId,
name: `Test Project ${group2ProjectId}`,
created_at: new Date().toISOString(),
})
await insertRow(postgres, 'posthog_team', {
id: group2TeamId,
name: `Test Team ${group2TeamId}`,
- organization_id: 'ca30f2ec-e9a4-4001-bf27-3ef194086068',
+ organization_id: organizationId,
project_id: group2ProjectId,
uuid: new UUIDT().toString(),
api_token: `test-api-token-${group2TeamId}`,
@@ -1515,8 +1513,8 @@ describe('PostgresGroupRepository Integration', () => {
})
it('should handle different projects independently', async () => {
- const localTeamId1 = 10 as TeamId // Use unique IDs for this test
- const localTeamId2 = 11 as TeamId
+ const localTeamId1 = uniqueTestId() as TeamId // Use unique IDs for this test
+ const localTeamId2 = uniqueTestId() as TeamId
await insertTestTeam(localTeamId1)
await insertTestTeam(localTeamId2)
@@ -1745,7 +1743,7 @@ describe('PostgresGroupRepository Integration', () => {
it('should return empty arrays for projects with no group types', async () => {
await insertTestTeam(teamId)
- const localTeamId2 = 10 as TeamId
+ const localTeamId2 = uniqueTestId() as TeamId
await insertTestTeam(localTeamId2)
const result = await repository.fetchGroupTypesByProjectIds([
@@ -1777,8 +1775,8 @@ describe('PostgresGroupRepository Integration', () => {
})
it('should fetch group types for multiple projects', async () => {
- const localTeamId1 = 10 as TeamId
- const localTeamId2 = 11 as TeamId
+ const localTeamId1 = uniqueTestId() as TeamId
+ const localTeamId2 = uniqueTestId() as TeamId
await insertTestTeam(localTeamId1)
await insertTestTeam(localTeamId2)
@@ -1804,8 +1802,8 @@ describe('PostgresGroupRepository Integration', () => {
})
it('should handle mix of projects with and without group types', async () => {
- const localTeamId1 = 12 as TeamId
- const localTeamId2 = 13 as TeamId
+ const localTeamId1 = uniqueTestId() as TeamId
+ const localTeamId2 = uniqueTestId() as TeamId
await insertTestTeam(localTeamId1)
await insertTestTeam(localTeamId2)
@@ -1843,7 +1841,7 @@ describe('PostgresGroupRepository Integration', () => {
it('should return empty arrays for teams with no group types', async () => {
await insertTestTeam(teamId)
- const localTeamId2 = 20 as TeamId
+ const localTeamId2 = uniqueTestId() as TeamId
await insertTestTeam(localTeamId2)
const result = await repository.fetchGroupTypesByTeamIds([teamId, localTeamId2])
@@ -1872,8 +1870,8 @@ describe('PostgresGroupRepository Integration', () => {
})
it('should fetch group types for multiple teams', async () => {
- const localTeamId1 = 21 as TeamId
- const localTeamId2 = 22 as TeamId
+ const localTeamId1 = uniqueTestId() as TeamId
+ const localTeamId2 = uniqueTestId() as TeamId
await insertTestTeam(localTeamId1)
await insertTestTeam(localTeamId2)
@@ -1896,8 +1894,8 @@ describe('PostgresGroupRepository Integration', () => {
})
it('should handle mix of teams with and without group types', async () => {
- const localTeamId1 = 23 as TeamId
- const localTeamId2 = 24 as TeamId
+ const localTeamId1 = uniqueTestId() as TeamId
+ const localTeamId2 = uniqueTestId() as TeamId
await insertTestTeam(localTeamId1)
await insertTestTeam(localTeamId2)
@@ -2043,7 +2041,7 @@ describe('PostgresGroupRepository Integration', () => {
})
it('should handle multiple teams', async () => {
- const localTeamId2 = 25 as TeamId
+ const localTeamId2 = uniqueTestId() as TeamId
await insertTestTeam(localTeamId2)
await repository.insertGroupType(localTeamId2, localTeamId2 as ProjectId, 'company', 0, TEST_TIMESTAMP)
diff --git a/nodejs/src/common/kafka/producer.integration.test.ts b/nodejs/src/common/kafka/producer.integration.test.ts
index ae2f589ba9d8..bcc383b29255 100644
--- a/nodejs/src/common/kafka/producer.integration.test.ts
+++ b/nodejs/src/common/kafka/producer.integration.test.ts
@@ -1,7 +1,7 @@
import * as net from 'net'
import { AdminClient, LibrdKafkaError } from 'node-rdkafka'
-import { createTopics } from '~/tests/helpers/kafka'
+import { ensureKafkaTopics } from '~/tests/helpers/kafka'
import { KafkaProducerWrapper } from './producer'
@@ -58,7 +58,7 @@ describe('KafkaProducerWrapper.checkTopicExists', () => {
await deleteTopic(topicExists)
await deleteTopic(topicMissing)
- await createTopics(KAFKA_CONFIG, [topicExists])
+ await ensureKafkaTopics([topicExists])
})
afterAll(async () => {
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.serial.test.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
similarity index 95%
rename from nodejs/src/common/persons/repositories/postgres-person-repository.serial.test.ts
rename to nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
index a7c004ba4460..c5ecc066001b 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.serial.test.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
@@ -1,4 +1,3 @@
-// Serial: resets shared Postgres and Redis while tests depend on the reset-created default team.
import { mockProducer } from '~/tests/helpers/mocks/producer.mock'
import { DateTime } from 'luxon'
@@ -11,7 +10,7 @@ import { closeHub, createHub } from '~/common/utils/db/hub'
import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'
import { parseJSON } from '~/common/utils/json-parse'
import { NoRowsUpdatedError, UUIDT } from '~/common/utils/utils'
-import { createTeam, insertRow, resetTestDatabase } from '~/tests/helpers/sql'
+import { createTeam, createTestTeamFixture, insertRow } from '~/tests/helpers/sql'
import { Hub, InternalPerson, PropertyUpdateOperation, Team } from '~/types'
import {
@@ -29,24 +28,29 @@ describe('PostgresPersonRepository', () => {
let hub: Hub
let postgres: PostgresRouter
let repository: PostgresPersonRepository
+ let team: Team
- beforeEach(async () => {
+ beforeAll(async () => {
hub = await createHub()
- await resetTestDatabase()
postgres = hub.postgres
repository = new PostgresPersonRepository(postgres, {
calculatePropertiesSize: 0,
personPropertiesDbConstraintLimitBytes: 1024 * 1024, // 1MB for tests
personPropertiesTrimTargetBytes: 512 * 1024,
})
-
- const redis = await hub.redisPool.acquire()
- await redis.flushdb()
- await hub.redisPool.release(redis)
})
- afterEach(async () => {
+ afterAll(async () => {
await closeHub(hub)
+ })
+
+ beforeEach(async () => {
+ team = (await createTestTeamFixture(postgres)).team
+ })
+
+ afterEach(() => {
+ // The hub outlives each test now, so spies on it must not.
+ jest.restoreAllMocks()
jest.clearAllMocks()
})
@@ -78,14 +82,12 @@ describe('PostgresPersonRepository', () => {
describe('fetchPerson()', () => {
it('returns undefined if person does not exist', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await repository.fetchPerson(team.id, 'some_id')
expect(person).toEqual(undefined)
})
it('returns person object if person exists', async () => {
- const team = await getFirstTeam(hub.postgres)
const createdPerson = await createTestPerson(team.id, 'some_id', { foo: 'bar' })
const person = await repository.fetchPerson(team.id, 'some_id')
@@ -103,15 +105,12 @@ describe('PostgresPersonRepository', () => {
})
it('throws error when both forUpdate and useReadReplica are true', async () => {
- const team = await getFirstTeam(hub.postgres)
-
await expect(
repository.fetchPerson(team.id, 'some_id', { forUpdate: true, useReadReplica: true })
).rejects.toThrow("can't enable both forUpdate and useReadReplica in db::fetchPerson")
})
it('uses read replica when useReadReplica is true', async () => {
- const team = await getFirstTeam(hub.postgres)
const createdPerson = await createTestPerson(team.id, 'some_id', { foo: 'bar' })
// Mock the postgres query to verify it's called with the right parameters
@@ -148,7 +147,6 @@ describe('PostgresPersonRepository', () => {
})
it('uses write connection when useReadReplica is false', async () => {
- const team = await getFirstTeam(hub.postgres)
const createdPerson = await createTestPerson(team.id, 'some_id', { foo: 'bar' })
// Mock the postgres query to verify it's called with the right parameters
@@ -185,8 +183,6 @@ describe('PostgresPersonRepository', () => {
})
it('adds FOR UPDATE clause when forUpdate is true', async () => {
- const team = await getFirstTeam(hub.postgres)
-
// Mock the postgres query to verify the SQL contains FOR UPDATE
const mockQuery = jest.spyOn(postgres, 'query').mockResolvedValue({
rows: [],
@@ -263,7 +259,6 @@ describe('PostgresPersonRepository', () => {
}
it('excludes tombstoned persons from person reads', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'tombstoned-person-did')
await tombstonePerson(person)
@@ -280,7 +275,6 @@ describe('PostgresPersonRepository', () => {
})
it('excludes tombstoned distinct id mappings from reads while live mappings still resolve', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'live-did')
await repository.addDistinctId(person, 'dead-did', 0)
await tombstoneDistinctId(team.id, 'dead-did')
@@ -297,7 +291,6 @@ describe('PostgresPersonRepository', () => {
})
it('updatePerson does not touch a tombstoned person', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'guard-update-did')
await tombstonePerson(person)
@@ -311,7 +304,6 @@ describe('PostgresPersonRepository', () => {
})
it('updatePersonAssertVersion does not touch a tombstoned person even at the matching version', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'guard-assert-did')
await tombstonePerson(person)
@@ -326,7 +318,6 @@ describe('PostgresPersonRepository', () => {
})
it('updatePersonsBatch skips tombstoned persons and leaves the death version intact', async () => {
- const team = await getFirstTeam(hub.postgres)
const livePerson = await createTestPerson(team.id, 'guard-batch-live-did')
const deadPerson = await createTestPerson(team.id, 'guard-batch-dead-did')
await tombstonePerson(deadPerson)
@@ -365,7 +356,6 @@ describe('PostgresPersonRepository', () => {
repository.moveDistinctIdsFromPersons([source], target),
],
])('%s moves only live distinct id mappings', async (_name, move) => {
- const team = await getFirstTeam(hub.postgres)
const source = await createTestPerson(team.id, 'guard-move-live-did')
const target = await createTestPerson(team.id, 'guard-move-target-did')
await repository.addDistinctId(source, 'guard-move-dead-did', 0)
@@ -380,7 +370,6 @@ describe('PostgresPersonRepository', () => {
})
it('createPerson revives a tombstoned person and its distinct id at death_version + 1', async () => {
- const team = await getFirstTeam(hub.postgres)
const uuid = new UUIDT().toString()
const first = await revivalRepository.createPerson(
TIMESTAMP,
@@ -431,7 +420,6 @@ describe('PostgresPersonRepository', () => {
})
it('createPerson returns CreationConflict against a live person with the same uuid', async () => {
- const team = await getFirstTeam(hub.postgres)
const uuid = new UUIDT().toString()
const first = await revivalRepository.createPerson(
TIMESTAMP,
@@ -485,7 +473,6 @@ describe('PostgresPersonRepository', () => {
// throw escapes the conflict branch entirely, failing the merge saga that reaches
// createPerson through inTransaction. `repository` has no allowlist, so it takes
// that path rather than the ON CONFLICT one.
- const team = await getFirstTeam(hub.postgres)
const uuid = new UUIDT().toString()
const first = await repository.createPerson(TIMESTAMP, { a: 1 }, {}, {}, team.id, null, false, uuid, {
distinctId: 'tx-uuid-did',
@@ -509,7 +496,6 @@ describe('PostgresPersonRepository', () => {
})
it('createPerson dedupes repeated distinct ids instead of failing the multi-insert', async () => {
- const team = await getFirstTeam(hub.postgres)
const uuid = new UUIDT().toString()
const result = await revivalRepository.createPerson(
@@ -534,7 +520,6 @@ describe('PostgresPersonRepository', () => {
})
it('createPerson undoes its insert when a distinct id is owned by a live mapping', async () => {
- const team = await getFirstTeam(hub.postgres)
await createTestPerson(team.id, 'contested-did')
const uuid = new UUIDT().toString()
@@ -566,7 +551,6 @@ describe('PostgresPersonRepository', () => {
})
it('addDistinctId revives a tombstoned mapping, repointing it at the new person', async () => {
- const team = await getFirstTeam(hub.postgres)
const newOwner = await createTestPerson(team.id, 'adder-did')
const oldOwner = await createTestPerson(team.id, 'old-owner-did')
await revivalRepository.addDistinctId(oldOwner, 'recycled-did', 0)
@@ -588,7 +572,6 @@ describe('PostgresPersonRepository', () => {
})
it('addDistinctId throws DistinctIdConflictError for a live mapping', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'conflict-adder-did')
await createTestPerson(team.id, 'already-owned-did')
@@ -598,7 +581,6 @@ describe('PostgresPersonRepository', () => {
})
it('isPersonLive is true for a live person and false for a tombstoned one', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'live-check-did')
await expect(repository.isPersonLive(person)).resolves.toBe(true)
@@ -624,7 +606,6 @@ describe('PostgresPersonRepository', () => {
}
it('claim and release leave no rows behind', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'mark-roundtrip-did')
const opId = new UUIDT().toString()
@@ -638,7 +619,6 @@ describe('PostgresPersonRepository', () => {
})
it('claiming a person held by a live operation throws PersonClaimedByLifecycleOpError', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'mark-conflict-did')
const sagaOpId = new UUIDT().toString()
// A delete saga's live claim: committed in its own transaction and held
@@ -658,7 +638,6 @@ describe('PostgresPersonRepository', () => {
})
it('release scoped to another team leaves the marks in place', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'mark-scoped-did')
const opId = new UUIDT().toString()
await repository.claimLifecycleMarks(opId, team.id, [
@@ -673,7 +652,6 @@ describe('PostgresPersonRepository', () => {
})
it('a released mark no longer blocks a new claim', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'mark-released-did')
const firstOpId = new UUIDT().toString()
await repository.claimLifecycleMarks(firstOpId, team.id, [
@@ -702,7 +680,6 @@ describe('PostgresPersonRepository', () => {
})
it('deletePerson tombstones the row at the exact death version with scrubbed properties', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'ts-delete-did', { secret: 'x' })
await tombstoneDistinctId(team.id, 'ts-delete-did')
@@ -724,7 +701,6 @@ describe('PostgresPersonRepository', () => {
})
it('deletePerson refuses while live distinct ids still point at the person', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'ts-blocked-did')
await expect(tombstoneRepository.deletePerson(person)).rejects.toThrow(PersonTombstoneBlockedError)
@@ -734,7 +710,6 @@ describe('PostgresPersonRepository', () => {
})
it('deletePersons tombstones fresh persons and skips already-tombstoned ones', async () => {
- const team = await getFirstTeam(hub.postgres)
const alreadyDead = await createTestPerson(team.id, 'ts-batch-dead-did')
const fresh = await createTestPerson(team.id, 'ts-batch-fresh-did')
await tombstoneDistinctId(team.id, 'ts-batch-dead-did')
@@ -752,7 +727,6 @@ describe('PostgresPersonRepository', () => {
describe('createPerson()', () => {
it('creates a person with basic properties', async () => {
- const team = await getFirstTeam(hub.postgres)
const uuid = new UUIDT().toString()
const properties = { name: 'John Doe', email: '[email protected]' }
@@ -784,7 +758,6 @@ describe('PostgresPersonRepository', () => {
})
it('creates a person with multiple distinct IDs', async () => {
- const team = await getFirstTeam(hub.postgres)
const uuid = new UUIDT().toString()
const properties = { name: 'Jane Doe' }
@@ -833,7 +806,6 @@ describe('PostgresPersonRepository', () => {
})
it('throws error when trying to create a person with the same distinct ID twice', async () => {
- const team = await getFirstTeam(hub.postgres)
const distinctId = 'duplicate-distinct-id'
const uuid1 = new UUIDT().toString()
const uuid2 = new UUIDT().toString()
@@ -886,7 +858,6 @@ describe('PostgresPersonRepository', () => {
describe('addDistinctId()', () => {
it('should add distinct ID to person', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'existing-distinct-id', { name: 'John Doe' })
const newDistinctId = 'new-distinct-id'
const version = 1
@@ -908,7 +879,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle adding distinct ID with different version', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'existing-distinct-id', { name: 'John Doe' })
const newDistinctId = 'another-distinct-id'
const version = 5
@@ -932,7 +902,6 @@ describe('PostgresPersonRepository', () => {
describe('deletePerson()', () => {
it('should delete person from postgres', async () => {
- const team = await getFirstTeam(hub.postgres)
const uuid = new UUIDT().toString()
const result = await repository.createPerson(TIMESTAMP, {}, {}, {}, team.id, null, true, uuid, {
distinctId: 'delete-test-distinct',
@@ -989,7 +958,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle deleting person that does not exist', async () => {
- const team = await getFirstTeam(hub.postgres)
const nonExistentPerson = {
id: '999999',
uuid: new UUIDT().toString(),
@@ -1013,7 +981,6 @@ describe('PostgresPersonRepository', () => {
describe('moveDistinctIds()', () => {
it('should move distinct IDs from source to target person', async () => {
- const team = await getFirstTeam(hub.postgres)
const sourcePerson = await createTestPerson(team.id, 'source-distinct-id', { name: 'Source Person' })
const targetPerson = await createTestPerson(team.id, 'target-distinct-id', { name: 'Target Person' })
@@ -1044,7 +1011,6 @@ describe('PostgresPersonRepository', () => {
})
it.skip('should handle target person not found', async () => {
- const team = await getFirstTeam(hub.postgres)
const sourcePerson = await createTestPerson(team.id, 'source-distinct-id', { name: 'Source Person' })
const nonExistentTargetPerson = {
id: '999999',
@@ -1069,7 +1035,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle source person not found', async () => {
- const team = await getFirstTeam(hub.postgres)
const targetPerson = await createTestPerson(team.id, 'target-distinct-id', { name: 'Target Person' })
const nonExistentSourcePerson = {
id: '888888',
@@ -1094,7 +1059,6 @@ describe('PostgresPersonRepository', () => {
})
it('should respect per-call move limit when provided', async () => {
- const team = await getFirstTeam(hub.postgres)
const limitedRepository = new PostgresPersonRepository(postgres, {})
const sourcePerson = await createTestPerson(team.id, 'source-distinct-id', { name: 'Source Person' })
@@ -1140,7 +1104,6 @@ describe('PostgresPersonRepository', () => {
})
it('should move all distinct IDs when no limit is configured', async () => {
- const team = await getFirstTeam(hub.postgres)
const unlimitedRepository = new PostgresPersonRepository(postgres, {}) // No limit
const sourcePerson = await createTestPerson(team.id, 'source-unlimited', { name: 'Source Person' })
@@ -1171,7 +1134,6 @@ describe('PostgresPersonRepository', () => {
})
it('should move distinct IDs in deterministic order when per-call limit is set', async () => {
- const team = await getFirstTeam(hub.postgres)
const limitedRepository = new PostgresPersonRepository(postgres, {})
const sourcePerson = await createTestPerson(team.id, 'source-deterministic', { name: 'Source Person' })
@@ -1226,7 +1188,6 @@ describe('PostgresPersonRepository', () => {
})
it('should move all distinct IDs when person has fewer than the per-call limit', async () => {
- const team = await getFirstTeam(hub.postgres)
const limitedRepository = new PostgresPersonRepository(postgres, {})
const sourcePerson = await createTestPerson(team.id, 'source-below-limit', { name: 'Source Person' })
@@ -1273,7 +1234,6 @@ describe('PostgresPersonRepository', () => {
describe('fetchPersonDistinctIds()', () => {
it('should fetch all distinct IDs when no limit is specified', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-distinct-id', { name: 'Test Person' })
// Add more distinct IDs
@@ -1291,7 +1251,6 @@ describe('PostgresPersonRepository', () => {
})
it('should fetch limited distinct IDs when limit is specified', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-limit-distinct', { name: 'Test Person' })
// Add more distinct IDs
@@ -1307,7 +1266,6 @@ describe('PostgresPersonRepository', () => {
})
it('should return distinct IDs in deterministic order', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'order-test-distinct', { name: 'Test Person' })
// Add distinct IDs in non-alphabetical order
@@ -1324,7 +1282,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle limit larger than available distinct IDs', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'large-limit-distinct', { name: 'Test Person' })
// Add only 2 more distinct IDs (total of 3)
@@ -1340,7 +1297,6 @@ describe('PostgresPersonRepository', () => {
})
it('should work with transactions', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'tx-distinct', { name: 'Test Person' })
await repository.addDistinctId(person, 'tx-distinct-2', 1)
@@ -1361,7 +1317,7 @@ describe('PostgresPersonRepository', () => {
})
it('should fetch persons by distinct IDs from multiple teams', async () => {
- const team1 = await getFirstTeam(hub.postgres)
+ const team1 = team
const team2Id = await createTeam(postgres, team1.organization_id)
// Create persons in different teams
@@ -1400,7 +1356,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle non-existent distinct IDs gracefully', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'existing-distinct', { name: 'Existing Person' })
const teamPersons = [
@@ -1417,7 +1372,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle single team person lookup', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'single-distinct', { name: 'Single Person' })
const teamPersons = [{ teamId: team.id as any, distinctId: 'single-distinct' }]
@@ -1432,7 +1386,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle duplicate team/distinctId pairs', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'duplicate-distinct', { name: 'Duplicate Person' })
const teamPersons = [
@@ -1449,7 +1402,6 @@ describe('PostgresPersonRepository', () => {
})
it('should include all required fields in InternalPersonWithDistinctId', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'fields-test', { name: 'Fields Test', age: 25 })
const teamPersons = [{ teamId: team.id as any, distinctId: 'fields-test' }]
@@ -1484,7 +1436,7 @@ describe('PostgresPersonRepository', () => {
['single team', 1],
['multiple teams', 2],
])('should fetch persons by person IDs (%s)', async (_label, teamCount) => {
- const team1 = await getFirstTeam(hub.postgres)
+ const team1 = team
const team2Id = teamCount > 1 ? await createTeam(postgres, team1.organization_id) : team1.id
const person1 = await createTestPerson(team1.id, 'pid-test-1', { name: 'Person 1' })
@@ -1504,7 +1456,7 @@ describe('PostgresPersonRepository', () => {
})
it('should not return persons from a different team even if their IDs were referenced', async () => {
- const team1 = await getFirstTeam(hub.postgres)
+ const team1 = team
const team2Id = await createTeam(postgres, team1.organization_id)
const team1Person = await createTestPerson(team1.id, 'cross-team-1', { name: 'Team 1 Person' })
@@ -1521,7 +1473,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle non-existent person IDs gracefully', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'existing-person', { name: 'Existing' })
const nonExistentId = new UUIDT().toString()
@@ -1535,7 +1486,6 @@ describe('PostgresPersonRepository', () => {
})
it('should deduplicate repeated (teamId, personId) pairs', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'dedup-person', { name: 'Dedup' })
const result = await repository.fetchPersonsByPersonIds([
@@ -1550,13 +1500,11 @@ describe('PostgresPersonRepository', () => {
describe('fetchDistinctIdsForPersons', () => {
it('returns empty object when no person ids provided', async () => {
- const team = await getFirstTeam(hub.postgres)
const result = await repository.fetchDistinctIdsForPersons(team.id, [])
expect(result).toEqual({})
})
it('returns distinct_ids keyed by int person_id, capped per person', async () => {
- const team = await getFirstTeam(hub.postgres)
const person1 = await createTestPerson(team.id, 'distinct-1-a', { name: 'Person 1' })
await repository.addDistinctId(person1, 'distinct-1-b', 0)
await repository.addDistinctId(person1, 'distinct-1-c', 0)
@@ -1575,7 +1523,7 @@ describe('PostgresPersonRepository', () => {
})
it('omits persons that have no distinct_ids in the target team', async () => {
- const team1 = await getFirstTeam(hub.postgres)
+ const team1 = team
const team2Id = await createTeam(postgres, team1.organization_id)
const personInTeam2 = await createTestPerson(team2Id, 'team2-only', { name: 'Team 2' })
@@ -1586,7 +1534,6 @@ describe('PostgresPersonRepository', () => {
describe('personPropertiesSize', () => {
it('should return properties size for existing person', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-distinct', {
name: 'John Doe',
@@ -1604,7 +1551,6 @@ describe('PostgresPersonRepository', () => {
})
it('should return 0 for non-existent person', async () => {
- const team = await getFirstTeam(hub.postgres)
const fakePersonId = '999999' // Use a numeric ID instead of UUID
const size = await repository.personPropertiesSize(fakePersonId, team.id)
@@ -1612,7 +1558,7 @@ describe('PostgresPersonRepository', () => {
})
it('should handle different persons correctly', async () => {
- const team1 = await getFirstTeam(hub.postgres)
+ const team1 = team
const team2Id = await createTeam(hub.postgres, team1.organization_id)
// Create person in team 1
@@ -1631,8 +1577,6 @@ describe('PostgresPersonRepository', () => {
})
it('should return larger size for person with more properties', async () => {
- const team = await getFirstTeam(hub.postgres)
-
// Create person with minimal properties
const minimalPerson = await createTestPerson(team.id, 'minimal-person', { name: 'Minimal' })
const minimalSize = await repository.personPropertiesSize(minimalPerson.id, team.id)
@@ -1672,7 +1616,6 @@ describe('PostgresPersonRepository', () => {
describe('updatePerson', () => {
it('should update person properties successfully', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-distinct', { name: 'John', age: 25 })
const update = { properties: { name: 'Jane', age: 30, city: 'New York' } }
@@ -1693,7 +1636,6 @@ describe('PostgresPersonRepository', () => {
})
it('should update is_identified field', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-distinct', { name: 'John' })
const update = { is_identified: true }
@@ -1708,7 +1650,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle version conflicts correctly', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-distinct', { name: 'John' })
// First update
@@ -1732,7 +1673,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle transaction parameter correctly', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-distinct', { name: 'John' })
await postgres.transaction(PostgresUse.PERSONS_WRITE, 'test-transaction', async (tx) => {
@@ -1754,7 +1694,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle tag parameter correctly', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-distinct', { name: 'John' })
const update = { properties: { name: 'Jane' } }
@@ -1769,7 +1708,6 @@ describe('PostgresPersonRepository', () => {
})
it('should throw NoRowsUpdatedError when person does not exist', async () => {
- const team = await getFirstTeam(hub.postgres)
const nonExistentPerson: InternalPerson = {
id: '1234567890',
team_id: team.id,
@@ -1791,7 +1729,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle updatePersonAssertVersion with optimistic concurrency control', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-distinct', { name: 'John' })
// Create a PersonUpdate object
@@ -1829,7 +1766,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle updatePersonAssertVersion with version mismatch', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-distinct', { name: 'John' })
// Create a PersonUpdate with an outdated version
@@ -1867,8 +1803,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle updatePersonAssertVersion with non-existent person', async () => {
- const team = await getFirstTeam(hub.postgres)
-
// Create a PersonUpdate for a non-existent person
const personUpdate = {
id: '999999',
@@ -1899,7 +1833,6 @@ describe('PostgresPersonRepository', () => {
})
it('should merge properties_to_set into properties when updating', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-merge-set', { existing: 'value', to_update: 'old' })
const personUpdate = {
@@ -1937,7 +1870,6 @@ describe('PostgresPersonRepository', () => {
})
it('should apply properties_to_unset when updating', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-unset', {
keep: 'value',
remove_me: 'will be removed',
@@ -1975,7 +1907,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle combined properties_to_set and properties_to_unset', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-combined', {
keep: 'value',
remove: 'will go',
@@ -2019,22 +1950,20 @@ describe('PostgresPersonRepository', () => {
})
describe('updateCohortsAndFeatureFlagsForMerge()', () => {
- let team: Team
let sourcePersonID: InternalPerson['id']
let targetPersonID: InternalPerson['id']
async function getAllHashKeyOverrides(): Promise<any> {
const result = await hub.postgres.query(
PostgresUse.PERSONS_WRITE,
- 'SELECT feature_flag_key, hash_key, person_id FROM posthog_featureflaghashkeyoverride',
- [],
+ 'SELECT feature_flag_key, hash_key, person_id FROM posthog_featureflaghashkeyoverride WHERE team_id = $1',
+ [team.id],
''
)
return result.rows
}
beforeEach(async () => {
- team = await getFirstTeam(hub.postgres)
const result = await repository.createPerson(
TIMESTAMP,
{},
@@ -2320,7 +2249,6 @@ describe('PostgresPersonRepository', () => {
describe('createPerson with oversized properties', () => {
it('should throw PersonPropertiesSizeViolationError when properties exceed size limit', async () => {
- const team = await getFirstTeam(hub.postgres)
const uuid = new UUIDT().toString()
const oversizedProperties = {
description: 'x'.repeat(200),
@@ -2371,8 +2299,6 @@ describe('PostgresPersonRepository', () => {
describe('updatePerson with oversized properties', () => {
it('should trim existing oversized person properties and update successfully', async () => {
- const team = await getFirstTeam(hub.postgres)
-
const normalPerson = await createTestPerson(team.id, 'test-oversized-update', {
name: 'John',
description: 'x'.repeat(120),
@@ -2404,7 +2330,6 @@ describe('PostgresPersonRepository', () => {
})
it('should reject update when current person is under limit but update would exceed it', async () => {
- const team = await getFirstTeam(hub.postgres)
const normalPerson = await createTestPerson(team.id, 'test-normal-person', { name: 'John' })
const mockPersonPropertiesSize = jest
@@ -2446,7 +2371,6 @@ describe('PostgresPersonRepository', () => {
})
it('should fail gracefully when trimming fails', async () => {
- const team = await getFirstTeam(hub.postgres)
const normalPerson = await createTestPerson(team.id, 'test-trim-failure', {
name: 'John',
description: 'x'.repeat(120),
@@ -2501,8 +2425,6 @@ describe('PostgresPersonRepository', () => {
})
it('should fail when protected properties alone exceed size limit and cannot be trimmed', async () => {
- const team = await getFirstTeam(hub.postgres)
-
const largeProtectedProperties = {
name: 'John Doe with a very long name that takes up significant space',
email: 'john.doe.with.an.extremely.long.email.address.that.should.be.protected@example.com',
@@ -2603,7 +2525,6 @@ describe('PostgresPersonRepository', () => {
describe('updatePersonAssertVersion with oversized properties', () => {
it('should throw PersonPropertiesSizeViolationError when properties exceed size limit', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-assert-oversized', { name: 'John' })
const originalQuery = postgres.query.bind(postgres)
@@ -2654,7 +2575,6 @@ describe('PostgresPersonRepository', () => {
describe('new metrics and error handling', () => {
it('should increment personPropertiesSizeViolationCounter with correct labels', async () => {
- const team = await getFirstTeam(hub.postgres)
const uuid = new UUIDT().toString()
const oversizedProperties = {
description: 'x'.repeat(200),
@@ -2699,7 +2619,6 @@ describe('PostgresPersonRepository', () => {
})
it('should increment oversizedPersonPropertiesTrimmedCounter when trimming succeeds', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-trimming-metrics', {
name: 'John',
description: 'x'.repeat(120),
@@ -2800,8 +2719,6 @@ describe('PostgresPersonRepository', () => {
describe('calculate properties size feature flag', () => {
it('should have identical output whether properties size calculation is enabled or disabled', async () => {
- const team = await getFirstTeam(hub.postgres)
-
const person1 = await createTestPerson(team.id, 'test-distinct-1', {
name: 'John',
age: 25,
@@ -2860,8 +2777,6 @@ describe('PostgresPersonRepository', () => {
})
it('should have identical behavior for updatePersonAssertVersion regardless of logging configuration', async () => {
- const team = await getFirstTeam(hub.postgres)
-
const person1 = await createTestPerson(team.id, 'test-assert-1', { name: 'John', data: 'x'.repeat(2000) })
const person2 = await createTestPerson(team.id, 'test-assert-2', { name: 'John', data: 'x'.repeat(2000) })
@@ -2918,7 +2833,6 @@ describe('PostgresPersonRepository', () => {
})
it('should work with default options (no logging)', async () => {
- const team = await getFirstTeam(hub.postgres)
const defaultRepository = new PostgresPersonRepository(postgres, {
calculatePropertiesSize: 0,
personPropertiesDbConstraintLimitBytes: 1024 * 1024,
@@ -2974,7 +2888,6 @@ describe('PostgresPersonRepository', () => {
})
it('should track JSON field sizes on createPerson', async () => {
- const team = await getFirstTeam(hub.postgres)
const properties = { name: 'Alice', email: '[email protected]', age: 25 }
const propertiesLastUpdatedAt = { name: '2024-01-15T10:30:00.000Z', email: '2024-01-15T10:30:00.000Z' }
const propertiesLastOperation = { name: PropertyUpdateOperation.Set, email: PropertyUpdateOperation.Set }
@@ -3020,7 +2933,6 @@ describe('PostgresPersonRepository', () => {
})
it('should track JSON field sizes on updatePerson with properties', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-metrics-update', { name: 'Bob' })
// Clear observe calls from createTestPerson
@@ -3063,7 +2975,6 @@ describe('PostgresPersonRepository', () => {
})
it('should only track metrics for fields being updated', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-metrics-partial', { name: 'Charlie' })
// Clear observe calls from createTestPerson
@@ -3088,7 +2999,6 @@ describe('PostgresPersonRepository', () => {
})
it('should handle large properties correctly', async () => {
- const team = await getFirstTeam(hub.postgres)
const largeProperties = {
name: 'David',
large_field: 'z'.repeat(100000), // 100KB of data
@@ -3134,7 +3044,6 @@ describe('PostgresPersonRepository', () => {
})
it('should not record metrics when update is empty', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'test-metrics-empty', { name: 'Eve' })
// Clear observe calls from createTestPerson
@@ -3153,12 +3062,10 @@ describe('PostgresPersonRepository', () => {
describe('fetchPersonsForUpdateByDistinctIds()', () => {
it('returns empty array for empty input', async () => {
- const team = await getFirstTeam(hub.postgres)
expect(await repository.fetchPersonsForUpdateByDistinctIds(team.id, [])).toEqual([])
})
it('resolves and locks multiple distinct ids in one query', async () => {
- const team = await getFirstTeam(hub.postgres)
const person1 = await createTestPerson(team.id, 'fold-anon-1', { name: 'One' })
const person2 = await createTestPerson(team.id, 'fold-anon-2', { name: 'Two' })
await repository.addDistinctId(person1, 'fold-anon-1b', 0)
@@ -3182,7 +3089,6 @@ describe('PostgresPersonRepository', () => {
describe('moveDistinctIdsFromPersons()', () => {
it('moves all distinct ids from multiple sources to the target', async () => {
- const team = await getFirstTeam(hub.postgres)
const source1 = await createTestPerson(team.id, 'fold-source-1', {})
const source2 = await createTestPerson(team.id, 'fold-source-2', {})
const target = await createTestPerson(team.id, 'fold-target', {})
@@ -3209,7 +3115,6 @@ describe('PostgresPersonRepository', () => {
})
it('treats sources without distinct ids as satisfied rather than failing', async () => {
- const team = await getFirstTeam(hub.postgres)
const source = await createTestPerson(team.id, 'fold-source-gone', {})
const target = await createTestPerson(team.id, 'fold-target-2', {})
@@ -3225,7 +3130,6 @@ describe('PostgresPersonRepository', () => {
})
it('returns success with no work for empty sources', async () => {
- const team = await getFirstTeam(hub.postgres)
const target = await createTestPerson(team.id, 'fold-target-3', {})
const result = await repository.moveDistinctIdsFromPersons([], target)
@@ -3236,7 +3140,6 @@ describe('PostgresPersonRepository', () => {
describe('deletePersons()', () => {
it('deletes multiple persons and returns one deletion message each', async () => {
- const team = await getFirstTeam(hub.postgres)
const person1 = await createTestPerson(team.id, 'fold-delete-1', {})
const person2 = await createTestPerson(team.id, 'fold-delete-2', {})
// Distinct ids reference persons via FK; clear them before deletion
@@ -3253,7 +3156,6 @@ describe('PostgresPersonRepository', () => {
})
it('returns no messages for already-deleted persons and empty input', async () => {
- const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'fold-delete-3', {})
const target = await createTestPerson(team.id, 'fold-delete-target-2', {})
await repository.moveDistinctIdsFromPersons([person], target)
@@ -3266,7 +3168,6 @@ describe('PostgresPersonRepository', () => {
describe('updateCohortsAndFeatureFlagsForMergeBatch()', () => {
it('moves overrides from multiple sources, keeping target values on conflict', async () => {
- const team = await getFirstTeam(hub.postgres)
const source1 = await createTestPerson(team.id, 'fold-ff-source-1', {})
const source2 = await createTestPerson(team.id, 'fold-ff-source-2', {})
const target = await createTestPerson(team.id, 'fold-ff-target', {})
@@ -3294,8 +3195,8 @@ describe('PostgresPersonRepository', () => {
const result = await hub.postgres.query(
PostgresUse.PERSONS_WRITE,
- 'SELECT feature_flag_key, hash_key, person_id FROM posthog_featureflaghashkeyoverride',
- [],
+ 'SELECT feature_flag_key, hash_key, person_id FROM posthog_featureflaghashkeyoverride WHERE team_id = $1',
+ [team.id],
''
)
expect(result.rows).toEqual(
@@ -3308,7 +3209,6 @@ describe('PostgresPersonRepository', () => {
})
it('is a no-op for empty sources', async () => {
- const team = await getFirstTeam(hub.postgres)
const target = await createTestPerson(team.id, 'fold-ff-target-2', {})
await repository.updateCohortsAndFeatureFlagsForMergeBatch(team.id, [], target.id)
@@ -3316,17 +3216,6 @@ describe('PostgresPersonRepository', () => {
})
})
-// Helper function from the original test file
-async function getFirstTeam(postgres: PostgresRouter): Promise<Team> {
- const teams = await postgres.query(
- PostgresUse.COMMON_WRITE,
- 'SELECT * FROM posthog_team LIMIT 1',
- [],
- 'getFirstTeam'
- )
- return teams.rows[0]
-}
-
async function fetchPersonByPersonId(hub: Hub, teamId: number, personId: string): Promise<any | undefined> {
const selectResult = await hub.postgres.query(
PostgresUse.PERSONS_WRITE,
diff --git a/nodejs/src/logs/__snapshots__/logs-ingestion-consumer.serial.test.ts.snap b/nodejs/src/logs/__snapshots__/logs-ingestion-consumer.test.ts.snap
similarity index 68%
rename from nodejs/src/logs/__snapshots__/logs-ingestion-consumer.serial.test.ts.snap
rename to nodejs/src/logs/__snapshots__/logs-ingestion-consumer.test.ts.snap
index 3dc959b217b3..36ed54ed5ec4 100644
--- a/nodejs/src/logs/__snapshots__/logs-ingestion-consumer.serial.test.ts.snap
+++ b/nodejs/src/logs/__snapshots__/logs-ingestion-consumer.test.ts.snap
@@ -5,8 +5,8 @@ exports[`LogsIngestionConsumer general should process a valid log message 1`] =
{
"json-parse": "false",
"retention-days": "14",
- "team_id": "2",
- "token": "THIS IS NOT A TOKEN FOR TEAM 2",
+ "team_id": "TEAM_ID",
+ "token": "<REPLACED-UUID-0>",
},
]
`;
@@ -16,20 +16,20 @@ exports[`LogsIngestionConsumer general should process multiple log messages 1`]
{
"json-parse": "false",
"retention-days": "14",
- "team_id": "2",
- "token": "THIS IS NOT A TOKEN FOR TEAM 2",
+ "team_id": "TEAM_ID",
+ "token": "<REPLACED-UUID-1>",
},
{
"json-parse": "false",
"retention-days": "14",
- "team_id": "2",
- "token": "THIS IS NOT A TOKEN FOR TEAM 2",
+ "team_id": "TEAM_ID",
+ "token": "<REPLACED-UUID-1>",
},
{
"json-parse": "false",
"retention-days": "14",
- "team_id": "2",
- "token": "THIS IS NOT A TOKEN FOR TEAM 2",
+ "team_id": "TEAM_ID",
+ "token": "<REPLACED-UUID-1>",
},
]
`;
@@ -39,8 +39,8 @@ exports[`LogsIngestionConsumer message parsing and validation should overwrite e
{
"json-parse": "false",
"retention-days": "14",
- "team_id": "2",
- "token": "THIS IS NOT A TOKEN FOR TEAM 2",
+ "team_id": "TEAM_ID",
+ "token": "<REPLACED-UUID-3>",
},
]
`;
@@ -51,8 +51,8 @@ exports[`LogsIngestionConsumer message parsing and validation should preserve ka
"json-parse": "false",
"myHeader": "hello",
"retention-days": "14",
- "team_id": "2",
- "token": "THIS IS NOT A TOKEN FOR TEAM 2",
+ "team_id": "TEAM_ID",
+ "token": "<REPLACED-UUID-2>",
},
]
`;
diff --git a/nodejs/src/logs/logs-ingestion-consumer.serial.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.ts
similarity index 96%
rename from nodejs/src/logs/logs-ingestion-consumer.serial.test.ts
rename to nodejs/src/logs/logs-ingestion-consumer.test.ts
index 9793f37a6107..6325ee24c658 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.serial.test.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts
@@ -1,4 +1,3 @@
-// Serial: resets shared Postgres and relies on the reset-created default team.
import { mockProducer, mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'
import { metrics as metricsApi } from '@opentelemetry/api'
@@ -17,12 +16,11 @@ import { KAFKA_APP_METRICS_2, KAFKA_LOGS_CLICKHOUSE, KAFKA_LOGS_INGESTION_DLQ }
import { APP_METRICS_OUTPUT, AppMetricsOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
-import { deleteKeysWithPrefix } from '~/common/redis/_tests/redis'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { PostgresUse } from '~/common/utils/db/postgres'
import { parseJSON } from '~/common/utils/json-parse'
import { forSnapshot } from '~/tests/helpers/snapshots'
-import { createTeam, getFirstTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'
+import { createTeam, createTestTeamFixture, getTeam } from '~/tests/helpers/sql'
import { Hub, Team } from '~/types'
import { getDefaultTracesIngestionConsumerConfig } from './config'
@@ -51,13 +49,14 @@ import type { LogsMetricsEmitter } from './metrics-rules/metrics-emitter'
import { LOGS_DLQ_OUTPUT, LOGS_OUTPUT, LogsDlqOutput, LogsOutput } from './outputs/outputs'
import { compileRuleSet } from './sampling/compile-rules'
import type { SamplingRulesCache } from './sampling/sampling-rules-cache'
-import { BASE_REDIS_KEY } from './services/logs-rate-limiter.service'
import { TracesIngestionConsumer } from './traces-ingestion-consumer'
import { LogsTransformerService } from './transformations/logs-transformer.service'
const DEFAULT_TEST_TIMEOUT = 5000
jest.setTimeout(DEFAULT_TEST_TIMEOUT)
+const SNAPSHOT_OVERRIDES = { overrides: { team_id: 'TEAM_ID' } }
+
jest.mock('~/common/utils/posthog', () => {
const original = jest.requireActual('~/common/utils/posthog')
return {
@@ -257,16 +256,14 @@ describe('LogsIngestionConsumer', () => {
jest.spyOn(Date.prototype, 'toISOString').mockReturnValue(fixedTime.toISO()!)
offsetIncrementer = 0
- await resetTestDatabase()
hub = await createHub()
- team = await getFirstTeam(hub.postgres)
+ team = (await createTestTeamFixture(hub.postgres)).team
const team2Id = await createTeam(hub.postgres, team.organization_id)
team2 = (await getTeam(hub.postgres, team2Id))!
consumer = await createLogsIngestionConsumer(hub)
- await deleteKeysWithPrefix(consumer['redis'], BASE_REDIS_KEY)
logMessageDroppedCounterSpy = jest.spyOn(logMessageDroppedCounter, 'inc')
recordLogMessageDroppedSpy = jest.spyOn(otelMetrics, 'recordLogMessageDropped')
@@ -340,7 +337,12 @@ describe('LogsIngestionConsumer', () => {
await waitForBackgroundTasks(consumer.processKafkaBatch(messages))
- expect(forSnapshot(getProducedKafkaMessages().map((m) => m.headers))).toMatchSnapshot()
+ expect(
+ forSnapshot(
+ getProducedKafkaMessages().map((m) => m.headers),
+ SNAPSHOT_OVERRIDES
+ )
+ ).toMatchSnapshot()
})
it('should process multiple log messages', async () => {
@@ -357,7 +359,12 @@ describe('LogsIngestionConsumer', () => {
const producedMessages = getProducedKafkaMessages()
expect(producedMessages).toHaveLength(3)
- expect(forSnapshot(producedMessages.map((m) => m.headers))).toMatchSnapshot()
+ expect(
+ forSnapshot(
+ producedMessages.map((m) => m.headers),
+ SNAPSHOT_OVERRIDES
+ )
+ ).toMatchSnapshot()
})
})
@@ -395,7 +402,12 @@ describe('LogsIngestionConsumer', () => {
await waitForBackgroundTasks(consumer.processKafkaBatch(messages))
const producedMessages = getProducedKafkaMessages()
- expect(forSnapshot(producedMessages.map((m) => m.headers))).toMatchSnapshot()
+ expect(
+ forSnapshot(
+ producedMessages.map((m) => m.headers),
+ SNAPSHOT_OVERRIDES
+ )
+ ).toMatchSnapshot()
})
it('should overwrite existing headers', async () => {
@@ -406,7 +418,12 @@ describe('LogsIngestionConsumer', () => {
})
await waitForBackgroundTasks(consumer.processKafkaBatch(messages))
- expect(forSnapshot(getProducedKafkaMessages().map((m) => m.headers))).toMatchSnapshot()
+ expect(
+ forSnapshot(
+ getProducedKafkaMessages().map((m) => m.headers),
+ SNAPSHOT_OVERRIDES
+ )
+ ).toMatchSnapshot()
})
it('should handle parse errors gracefully', async () => {
@@ -1747,7 +1764,6 @@ describe('LogsIngestionConsumer', () => {
{},
{ samplingRulesCache: mockSamplingCache as SamplingRulesCache }
)
- await deleteKeysWithPrefix(consumer['redis'], BASE_REDIS_KEY)
})
it('should emit sampling_records_dropped_by_rule when head sampling drops log lines', async () => {
@@ -1823,7 +1839,6 @@ describe('LogsIngestionConsumer', () => {
{ LOGS_BILLING_PRORATE_ENABLED: true },
{ samplingRulesCache: mockSamplingCache as SamplingRulesCache }
)
- await deleteKeysWithPrefix(consumer['redis'], BASE_REDIS_KEY)
await sendDroppedAndKeptMessages()
@@ -1850,7 +1865,6 @@ describe('LogsIngestionConsumer', () => {
{ LOGS_BILLING_PRORATE_ENABLED: true },
{ samplingRulesCache: mockSamplingCache as SamplingRulesCache }
)
- await deleteKeysWithPrefix(consumer['redis'], BASE_REDIS_KEY)
}
const message = await createMultiRecordKafkaMessage(
@@ -1900,7 +1914,6 @@ describe('LogsIngestionConsumer', () => {
metricsEmitter: mockEmitter as unknown as LogsMetricsEmitter,
...depsPartial,
})
- await deleteKeysWithPrefix(consumer['redis'], BASE_REDIS_KEY)
}
beforeEach(async () => {
@@ -2023,62 +2036,6 @@ describe('LogsIngestionConsumer', () => {
})
})
- describe('thread relief', () => {
- jest.setTimeout(30000)
-
- beforeEach(async () => {
- // Parent beforeEach mocks Date.now/toISOString — restore for real-time tracking.
- jest.spyOn(Date, 'now').mockRestore()
- jest.spyOn(Date.prototype, 'toISOString').mockRestore()
-
- // Enable PII scrub + JSON parse so processLogMessageBuffer does real CPU work
- // (without these settings it short-circuits and never decodes the buffer).
- await hub.postgres.query(
- PostgresUse.COMMON_WRITE,
- `UPDATE posthog_team SET logs_settings = $1 WHERE id = $2`,
- [JSON.stringify({ pii_scrub_logs: true, json_parse_logs: true }), team.id],
- 'updateTeamLogsForThreadRelief'
- )
- hub.teamManager['lazyLoader'].markForRefresh(String(team.id))
- })
-
- it('should process large batches without blocking the main thread', async () => {
- // Body large enough that JSON parse + PII scrub do meaningful sync work per message.
- const body = JSON.stringify({
- user_id: 'usr_abc123',
- email: '[email protected]',
- nested: { a: 1, b: 'two', c: [1, 2, 3, 4, 5] },
- message: 'A long log message ' + 'x'.repeat(500),
- })
-
- const numberToTest = 2000
- const messages = await createKafkaMessages(
- Array.from({ length: numberToTest }, () => ({ message: body })),
- { token: team.api_token }
- )
-
- // Track event-loop lag only during the consumer's processing.
- let lastCheck = Date.now()
- let longestDelay = 0
- const interval = setInterval(() => {
- longestDelay = Math.max(longestDelay, Date.now() - lastCheck)
- lastCheck = Date.now()
- }, 0)
-
- try {
- await waitForBackgroundTasks(consumer.processKafkaBatch(messages))
- } finally {
- clearInterval(interval)
- }
-
- const logsMessages = getProducedKafkaMessages().filter((m) => m.topic === 'clickhouse_logs_test')
- expect(logsMessages).toHaveLength(numberToTest)
-
- console.log(`[thread-relief] longestDelay = ${longestDelay}ms`)
- expect(longestDelay).toBeLessThan(120)
- })
- })
-
describe('TracesIngestionConsumer billing identity', () => {
const createTracesIngestionConsumer = (configOverrides: Record<string, any> = {}): TracesIngestionConsumer => {
const tracesConsumer = new TracesIngestionConsumer(
diff --git a/nodejs/src/logs/logs-ingestion-thread-relief.serial.test.ts b/nodejs/src/logs/logs-ingestion-thread-relief.serial.test.ts
new file mode 100644
index 000000000000..da35540ecd2e
--- /dev/null
+++ b/nodejs/src/logs/logs-ingestion-thread-relief.serial.test.ts
@@ -0,0 +1,174 @@
+// Serial: asserts an event-loop lag ceiling, so a worker competing for CPU fails it.
+import { mockProducer, mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'
+
+import { DateTime } from 'luxon'
+import { Message } from 'node-rdkafka'
+
+import { KAFKA_APP_METRICS_2, KAFKA_LOGS_CLICKHOUSE, KAFKA_LOGS_INGESTION_DLQ } from '~/common/config/kafka-topics'
+import { APP_METRICS_OUTPUT, AppMetricsOutput } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
+import { closeHub, createHub } from '~/common/utils/db/hub'
+import { PostgresUse } from '~/common/utils/db/postgres'
+import { createTestTeamFixture } from '~/tests/helpers/sql'
+import { Hub, Team } from '~/types'
+
+import { LogRecord, encodeLogRecords } from './log-record-avro'
+import { LogsIngestionConsumer } from './logs-ingestion-consumer'
+import { LOGS_DLQ_OUTPUT, LOGS_OUTPUT, LogsDlqOutput, LogsOutput } from './outputs/outputs'
+
+jest.setTimeout(30000)
+
+let offsetIncrementer = 0
+
+const createKafkaMessages = async (bodies: string[], headers: Record<string, string>): Promise<Message[]> => {
+ const avro = require('avsc')
+ const logRecordType = avro.Type.forSchema({
+ type: 'record',
+ name: 'LogRecord',
+ fields: [
+ { name: 'uuid', type: ['null', 'string'] },
+ { name: 'trace_id', type: ['null', 'bytes'] },
+ { name: 'span_id', type: ['null', 'bytes'] },
+ { name: 'trace_flags', type: ['null', 'int'] },
+ { name: 'timestamp', type: ['null', 'long'] },
+ { name: 'observed_timestamp', type: ['null', 'long'] },
+ { name: 'body', type: ['null', 'string'] },
+ { name: 'severity_text', type: ['null', 'string'] },
+ { name: 'severity_number', type: ['null', 'int'] },
+ { name: 'service_name', type: ['null', 'string'] },
+ { name: 'resource_attributes', type: ['null', { type: 'map', values: 'string' }] },
+ { name: 'instrumentation_scope', type: ['null', 'string'] },
+ { name: 'event_name', type: ['null', 'string'] },
+ { name: 'attributes', type: ['null', { type: 'map', values: 'string' }] },
+ ],
+ })
+
+ return await Promise.all(
+ bodies.map(async (body) => {
+ const record: LogRecord = {
+ uuid: `test-uuid-${offsetIncrementer}`,
+ trace_id: null,
+ span_id: null,
+ trace_flags: null,
+ timestamp: DateTime.now().toMillis() * 1000,
+ observed_timestamp: DateTime.now().toMillis() * 1000,
+ body,
+ severity_text: 'info',
+ severity_number: 9,
+ service_name: 'test-service',
+ resource_attributes: null,
+ instrumentation_scope: null,
+ event_name: null,
+ attributes: null,
+ }
+ const value = await encodeLogRecords(logRecordType, 'zstandard', [record])
+ return {
+ key: null,
+ value,
+ size: value.length,
+ topic: 'test',
+ offset: offsetIncrementer++,
+ timestamp: DateTime.now().toMillis(),
+ partition: 1,
+ headers: Object.entries(headers).map(([key, headerValue]) => ({
+ [key]: Buffer.from(headerValue),
+ })),
+ }
+ })
+ )
+}
+
+describe('LogsIngestionConsumer thread relief', () => {
+ let consumer: LogsIngestionConsumer
+ let hub: Hub
+ let team: Team
+
+ beforeEach(async () => {
+ offsetIncrementer = 0
+ hub = await createHub()
+ team = (await createTestTeamFixture(hub.postgres)).team
+
+ // PII scrub and JSON parse make processLogMessageBuffer do real CPU work per message.
+ // Without them it short-circuits and never decodes the buffer.
+ await hub.postgres.query(
+ PostgresUse.COMMON_WRITE,
+ `UPDATE posthog_team SET logs_settings = $1 WHERE id = $2`,
+ [JSON.stringify({ pii_scrub_logs: true, json_parse_logs: true }), team.id],
+ 'updateTeamLogsForThreadRelief'
+ )
+ hub.teamManager['lazyLoader'].markForRefresh(String(team.id))
+
+ consumer = new LogsIngestionConsumer(hub, {
+ ...hub,
+ outputs: new IngestionOutputs<AppMetricsOutput | LogsOutput | LogsDlqOutput>({
+ [APP_METRICS_OUTPUT]: new SingleIngestionOutput(
+ APP_METRICS_OUTPUT,
+ KAFKA_APP_METRICS_2,
+ mockProducer,
+ 'test'
+ ),
+ [LOGS_OUTPUT]: new SingleIngestionOutput(LOGS_OUTPUT, KAFKA_LOGS_CLICKHOUSE, mockProducer, 'test'),
+ [LOGS_DLQ_OUTPUT]: new SingleIngestionOutput(
+ LOGS_DLQ_OUTPUT,
+ KAFKA_LOGS_INGESTION_DLQ,
+ mockProducer,
+ 'test'
+ ),
+ }),
+ })
+ consumer['kafkaConsumer'] = {
+ connect: jest.fn(),
+ disconnect: jest.fn(),
+ isHealthy: jest.fn().mockReturnValue({ status: 'healthy' }),
+ } as any
+ await consumer.start()
+
+ jest.spyOn(hub.quotaLimiting, 'isTeamTokenQuotaLimited').mockResolvedValue(false)
+ })
+
+ afterEach(async () => {
+ await consumer.stop()
+ await closeHub(hub)
+ })
+
+ it('should process large batches without blocking the main thread', async () => {
+ const body = JSON.stringify({
+ user_id: 'usr_abc123',
+ email: '[email protected]',
+ nested: { a: 1, b: 'two', c: [1, 2, 3, 4, 5] },
+ message: 'A long log message ' + 'x'.repeat(500),
+ })
+
+ const numberToTest = 2000
+ const messages = await createKafkaMessages(
+ Array.from({ length: numberToTest }, () => body),
+ {
+ token: team.api_token,
+ }
+ )
+
+ let lastCheck = Date.now()
+ let longestDelay = 0
+ const interval = setInterval(() => {
+ longestDelay = Math.max(longestDelay, Date.now() - lastCheck)
+ lastCheck = Date.now()
+ }, 0)
+
+ try {
+ await (
+ await consumer.processKafkaBatch(messages)
+ ).backgroundTask
+ } finally {
+ clearInterval(interval)
+ }
+
+ // Counted rather than decoded: the logs output carries AVRO, not JSON.
+ const produced = mockProducerObserver
+ .getProducedMessages()
+ .filter((batch) => batch.topic === KAFKA_LOGS_CLICKHOUSE)
+ .flatMap((batch) => batch.messages)
+ expect(produced).toHaveLength(numberToTest)
+ expect(longestDelay).toBeLessThan(120)
+ })
+})
diff --git a/nodejs/tests/helpers/ingestion-e2e.ts b/nodejs/tests/helpers/ingestion-e2e.ts
index 919c6dbead39..86ad9957d799 100644
--- a/nodejs/tests/helpers/ingestion-e2e.ts
+++ b/nodejs/tests/helpers/ingestion-e2e.ts
@@ -51,7 +51,7 @@ import { PipelineEvent, PluginsServerConfig, ProjectId, RawClickHouseEvent, Redi
import { Clickhouse } from './clickhouse'
import { waitForExpect } from './expectations'
import { ensureKafkaTopics } from './kafka'
-import { createUserTeamAndOrganization } from './sql'
+import { createUserTeamAndOrganization, uniqueTestId } from './sql'
export const DEFAULT_TEAM: Team = {
id: 2,
@@ -512,7 +512,7 @@ export function createTestWithTeamIngester<T extends IngesterLike>(
const kafkaProducer = await KafkaProducerWrapper.create(serverConfig.KAFKA_CLIENT_RACK)
- const teamId = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)
+ const teamId = uniqueTestId()
const userId = teamId
const organizationId = new UUIDT().toString()
diff --git a/nodejs/tests/helpers/kafka.ts b/nodejs/tests/helpers/kafka.ts
index bdf24cd092e1..580bb548fa70 100644
--- a/nodejs/tests/helpers/kafka.ts
+++ b/nodejs/tests/helpers/kafka.ts
@@ -1,4 +1,4 @@
-import { AdminClient, CODES, KafkaConsumer, LibrdKafkaError } from 'node-rdkafka'
+import { AdminClient, CODES, LibrdKafkaError } from 'node-rdkafka'
import { defaultConfig, overrideWithEnv } from '~/common/config/config'
import {
@@ -111,17 +111,10 @@ export function createKafkaTestTopicName(baseTopic: string): string {
return `${baseTopic}_${Date.now()}_${Math.random().toString(16).slice(2)}`
}
-export async function createTopics(kafkaConfig: any, topics: string[]): Promise<void> {
- const client = AdminClient.create(kafkaConfig)
- await deleteAllTopics(kafkaConfig)
- await createTopicsWithClient(client, topics)
- client.disconnect()
-}
-
/**
* Create Kafka topics if they don't already exist, without deleting existing topics.
- * This preserves ClickHouse Kafka engine consumer connections, avoiding the slow
- * reconnection cycle that causes flaky tests.
+ * The broker is shared across parallel jest workers, so anything that deletes topics
+ * wholesale pulls the output topics out from under whatever else is mid-test.
*/
export async function ensureKafkaTopics(
topics: string[],
@@ -132,60 +125,3 @@ export async function ensureKafkaTopics(
await createTopicsWithClient(client, topics)
client.disconnect()
}
-
-export async function deleteAllTopics(kafkaConfig: any): Promise<void> {
- // Use a consumer to get metadata
- const consumer = new KafkaConsumer(
- {
- ...kafkaConfig,
- 'group.id': 'temp-metadata-group',
- },
- {}
- )
-
- await new Promise<void>((resolve, reject) => {
- consumer.on('ready', () => resolve())
- consumer.on('event.error', (err) => reject(err))
- consumer.connect()
- })
-
- // Get list of topics first
- const metadata = await new Promise<any>((resolve, reject) => {
- consumer.getMetadata({}, (err: any, metadata: any) => {
- if (err) {
- reject(err)
- } else {
- resolve(metadata)
- }
- })
- })
-
- consumer.disconnect()
-
- const topicsToDelete = metadata.topics.map((t: any) => t.name).filter((name: string) => !name.startsWith('__')) // skip internal topics
-
- if (topicsToDelete.length === 0) {
- console.log('No topics to delete.')
- return
- }
-
- // Use AdminClient to delete topics
- const adminClient = AdminClient.create(kafkaConfig)
- const timeout = 10000
-
- // Delete topics one by one
- for (const topic of topicsToDelete) {
- await new Promise<void>((resolve, reject) => {
- adminClient.deleteTopic(topic, timeout, (error: LibrdKafkaError) => {
- if (error) {
- console.error(`Failed to delete topic ${topic}:`, error)
- reject(error)
- } else {
- resolve()
- }
- })
- })
- }
-
- adminClient.disconnect()
-}
diff --git a/nodejs/tests/helpers/sql.ts b/nodejs/tests/helpers/sql.ts
index f96a180c08cd..0b3a0314fa11 100644
--- a/nodejs/tests/helpers/sql.ts
+++ b/nodejs/tests/helpers/sql.ts
@@ -1,4 +1,5 @@
import { DateTime } from 'luxon'
+import { randomInt } from 'node:crypto'
import { defaultConfig } from '~/common/config/config'
import { PERSON_COLUMNS } from '~/common/persons/repositories/postgres-person-repository'
@@ -8,6 +9,11 @@ import { UUIDT } from '~/common/utils/utils'
import { CookielessServerHashMode, InternalPerson, ProjectId, RawOrganization, RawPerson, Team } from '../../src/types'
import { assertRouterTargetsTestDatabase } from './database-guard'
+// Rows outlive their test file, so draw from the whole int4 range. Narrower schemes
+// (per-millisecond, per-file band) collide far more often. Not Math.random: tests mock
+// that to pin their own randomness, which would pin every id to one value too.
+export const uniqueTestId = (): number => randomInt(2_100_000_000)
+
export const commonUserId = 1001
export const commonOrganizationMembershipId = '0177364a-fc7b-0000-511c-137090b9e4e1'
export const commonOrganizationId = 'ca30f2ec-e9a4-4001-bf27-3ef194086068'
@@ -152,7 +158,14 @@ function getPostgresUseForTable(table: string): PostgresUse {
return PostgresUse.COMMON_WRITE
}
-export async function insertRow(postgres: PostgresRouter, table: string, objectProvided: Record<string, any>) {
+export async function insertRow(
+ postgres: PostgresRouter,
+ table: string,
+ objectProvided: Record<string, any>,
+ // Raw ON CONFLICT clause, for rows that are global rather than team-scoped and so
+ // can already exist when a suite no longer wipes the database.
+ onConflict = ''
+) {
// Handling of related fields
const { source__plugin_json, source__index_ts, source__frontend_tsx, source__site_ts, ...object } = objectProvided
@@ -178,6 +191,7 @@ export async function insertRow(postgres: PostgresRouter, table: string, objectP
postgresUse,
`INSERT INTO ${table} (${keys})
VALUES (${params})
+ ${onConflict}
RETURNING *`,
values,
`insertRow-${table}`
@@ -290,12 +304,12 @@ export async function createUserTeamAndOrganization(
await insertRow(db, 'posthog_team', teamData)
}
-export async function getTeams(postgres: PostgresRouter): Promise<Team[]> {
+async function queryTeams(postgres: PostgresRouter, where: string, params?: any[], limit = ''): Promise<Team[]> {
const selectResult = await postgres.query<Team>(
PostgresUse.COMMON_READ,
- 'SELECT * FROM posthog_team ORDER BY id',
- undefined,
- 'fetchAllTeams'
+ `SELECT * FROM posthog_team ${where} ORDER BY id ${limit}`,
+ params,
+ 'fetchTeams'
)
for (const row of selectResult.rows) {
row.project_id = parseInt(row.project_id as unknown as string) as ProjectId
@@ -303,13 +317,16 @@ export async function getTeams(postgres: PostgresRouter): Promise<Team[]> {
return selectResult.rows
}
+export async function getTeams(postgres: PostgresRouter): Promise<Team[]> {
+ return await queryTeams(postgres, '')
+}
+
export async function getTeam(postgres: PostgresRouter, teamId: Team['id']): Promise<Team | null> {
- const teams = await getTeams(postgres)
- return teams.find((team) => team.id === teamId) ?? null
+ return (await queryTeams(postgres, 'WHERE id = $1', [teamId]))[0] ?? null
}
export async function getFirstTeam(postgres: PostgresRouter): Promise<Team> {
- return (await getTeams(postgres))[0]
+ return (await queryTeams(postgres, '', undefined, 'LIMIT 1'))[0]
}
export const createOrganization = async (pg: PostgresRouter) => {
@@ -354,8 +371,7 @@ export const createTeam = async (
token?: string,
teamSettings?: Record<string, any>
): Promise<number> => {
- // KLUDGE: auto increment IDs can be racy in tests so we ensure IDs don't clash
- const id = Math.round(Math.random() * 1000000000)
+ const id = uniqueTestId()
let organizationId: string
let projectId: ProjectId
if (typeof projectOrOrganizationId === 'number') {
@@ -453,8 +469,7 @@ export const createAction = async (
bytecode: any[] | null = null,
actionSettings?: Record<string, any>
): Promise<number> => {
- // KLUDGE: auto increment IDs can be racy in tests so we ensure IDs don't clash
- const id = Math.round(Math.random() * 1000000000)
+ const id = uniqueTestId()
await insertRow(pg, 'posthog_action', {
id,
name,
@@ -480,7 +495,7 @@ export const createUser = async (pg: PostgresRouter, distinctId: string) => {
const user = await insertRow(pg, 'posthog_user', {
// Tests also insert fixed user IDs, which do not advance Postgres's sequence.
// Use a collision-resistant test ID rather than the stale sequence value.
- id: Math.round(Math.random() * 1000000000),
+ id: uniqueTestId(),
uuid: uuid,
password: 'gibberish',
first_name: 'PluginTest',
@@ -550,8 +565,7 @@ export const createCohort = async (
filters: string | null = null,
cohortSettings?: Record<string, any>
): Promise<number> => {
- // KLUDGE: auto increment IDs can be racy in tests so we ensure IDs don't clash
- const id = Math.round(Math.random() * 1000000000)
+ const id = uniqueTestId()
await insertRow(pg, 'posthog_cohort', {
id,
name,
diff --git a/nodejs/tests/ingestion/flag-evaluations-e2e.serial.test.ts b/nodejs/tests/ingestion/flag-evaluations-e2e.test.ts
similarity index 95%
rename from nodejs/tests/ingestion/flag-evaluations-e2e.serial.test.ts
rename to nodejs/tests/ingestion/flag-evaluations-e2e.test.ts
index f13ebe39c37e..ed4eb8b4fcfb 100644
--- a/nodejs/tests/ingestion/flag-evaluations-e2e.serial.test.ts
+++ b/nodejs/tests/ingestion/flag-evaluations-e2e.test.ts
@@ -1,4 +1,3 @@
-// Serial: resets the shared test database.
// Pins the full flag-evaluations shadow-write path — config → fork step → output
// registration → Kafka topic → ClickHouse Kafka engine → MV → flag_evaluations
// table — which no unit test can: a topic-key typo, a row column ClickHouse can't
@@ -24,7 +23,6 @@ import {
} from '~/tests/helpers/ingestion-e2e'
import { createTestIngestionOutputs, createTestMonitoringOutputs } from '~/tests/helpers/ingestion-outputs'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
-import { resetTestDatabase } from '~/tests/helpers/sql'
jest.mock('~/common/utils/logger')
@@ -47,14 +45,10 @@ describe('Flag evaluations shadow-routing E2E', () => {
beforeAll(async () => {
clickhouse = Clickhouse.create()
await ensureKafkaTopics(TEST_KAFKA_TOPICS)
- await resetTestDatabase()
- await clickhouse.resetTestDatabase()
await waitForClickHouseKafkaConsumer(clickhouse)
})
- afterAll(async () => {
- await resetTestDatabase()
- await clickhouse.resetTestDatabase()
+ afterAll(() => {
clickhouse.close()
})
diff --git a/nodejs/tests/ingestion/ingestion-e2e.serial.test.ts b/nodejs/tests/ingestion/ingestion-e2e.serial.test.ts
index 1965aaec24e4..3d0bdbce3e74 100644
--- a/nodejs/tests/ingestion/ingestion-e2e.serial.test.ts
+++ b/nodejs/tests/ingestion/ingestion-e2e.serial.test.ts
@@ -1,3 +1,4 @@
+// Serial until the startup topic check tolerates a transient metadata gap (see the follow-up PR).
import { DateTime } from 'luxon'
import { createHogTransformerService } from '~/cdp/hog-transformations/hog-transformer.service'
@@ -19,7 +20,7 @@ import {
} from '~/tests/helpers/ingestion-e2e'
import { createTestIngestionOutputs, createTestMonitoringOutputs } from '~/tests/helpers/ingestion-outputs'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
-import { createUserTeamAndOrganization, fetchPostgresPersons, resetTestDatabase } from '~/tests/helpers/sql'
+import { createUserTeamAndOrganization, fetchPostgresPersons, uniqueTestId } from '~/tests/helpers/sql'
import { GroupTypeIndex, InternalPerson } from '~/types'
// Mock the limiter so it always returns true
@@ -97,15 +98,11 @@ describe.each([
console.log('Creating Clickhouse client')
clickhouse = Clickhouse.create()
await ensureKafkaTopics(TEST_KAFKA_TOPICS)
- await resetTestDatabase()
- await clickhouse.resetTestDatabase()
await waitForClickHouseKafkaConsumer(clickhouse)
process.env.SITE_URL = 'https://example.com'
})
- afterAll(async () => {
- await resetTestDatabase()
- await clickhouse.resetTestDatabase()
+ afterAll(() => {
clickhouse.close()
})
@@ -3487,7 +3484,7 @@ describe.each([
{},
async ({ ingester, infra, team, kafkaProducer, token }) => {
// Create a second team
- const team2Id = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)
+ const team2Id = uniqueTestId()
await createUserTeamAndOrganization(
infra.postgres,
team2Id,
diff --git a/nodejs/tests/ingestion/person-properties-metadata.e2e.serial.test.ts b/nodejs/tests/ingestion/person-properties-metadata.e2e.test.ts
similarity index 98%
rename from nodejs/tests/ingestion/person-properties-metadata.e2e.serial.test.ts
rename to nodejs/tests/ingestion/person-properties-metadata.e2e.test.ts
index 9b3a1c1ac53f..d6a8769cb272 100644
--- a/nodejs/tests/ingestion/person-properties-metadata.e2e.serial.test.ts
+++ b/nodejs/tests/ingestion/person-properties-metadata.e2e.test.ts
@@ -19,7 +19,7 @@ import { waitForExpect } from '~/tests/helpers/expectations'
import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
import { createTestIngestionOutputs, createTestMonitoringOutputs } from '~/tests/helpers/ingestion-outputs'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
-import { createUserTeamAndOrganization, fetchPostgresPersons, resetTestDatabase } from '~/tests/helpers/sql'
+import { createUserTeamAndOrganization, fetchPostgresPersons, uniqueTestId } from '~/tests/helpers/sql'
import { PipelineEvent, PluginsServerConfig, ProjectId, Team } from '~/types'
jest.mock('~/common/utils/token-bucket', () => {
@@ -150,7 +150,7 @@ const createTestWithTeamIngester = (baseConfig: Partial<PluginsServerConfig> = {
})
const kafkaProducer = await KafkaProducerWrapper.create(infra.config.KAFKA_CLIENT_RACK)
- const teamId = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)
+ const teamId = uniqueTestId()
const userId = teamId
const organizationId = new UUIDT().toString()
@@ -212,14 +212,9 @@ describe('Person properties_last_updated_at and properties_last_operation behavi
beforeAll(async () => {
await ensureKafkaTopics(TEST_KAFKA_TOPICS)
- await resetTestDatabase()
process.env.SITE_URL = 'https://example.com'
})
- afterAll(async () => {
- await resetTestDatabase()
- })
-
testWithTeamIngester(
'does set properties_last_updated_at and properties_last_operation when creating person via $set',
{},
diff --git a/nodejs/tests/ingestion/person-updates-e2e.serial.test.ts b/nodejs/tests/ingestion/person-updates-e2e.test.ts
similarity index 97%
rename from nodejs/tests/ingestion/person-updates-e2e.serial.test.ts
rename to nodejs/tests/ingestion/person-updates-e2e.test.ts
index da9b23daa1de..a7dd3f4e87bc 100644
--- a/nodejs/tests/ingestion/person-updates-e2e.serial.test.ts
+++ b/nodejs/tests/ingestion/person-updates-e2e.test.ts
@@ -21,12 +21,11 @@ import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { UUIDT } from '~/common/utils/utils'
import { PersonBatchWritingDbWriteMode } from '~/ingestion/config'
import { IngestionConsumer } from '~/ingestion/ingestion-consumer'
-import { Clickhouse } from '~/tests/helpers/clickhouse'
import { waitForExpect } from '~/tests/helpers/expectations'
import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
import { createTestIngestionOutputs, createTestMonitoringOutputs } from '~/tests/helpers/ingestion-outputs'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
-import { createUserTeamAndOrganization, resetTestDatabase } from '~/tests/helpers/sql'
+import { createUserTeamAndOrganization, uniqueTestId } from '~/tests/helpers/sql'
import { PipelineEvent, ProjectId, Team } from '~/types'
jest.mock('~/common/utils/token-bucket', () => {
@@ -171,23 +170,13 @@ const formatConfigName = (config: PersonUpdateConfig): string => {
describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
const configName = formatConfigName(config)
- let clickhouse: Clickhouse
let infra: IngestionTestInfra
let kafkaProducer: KafkaProducerWrapper
let ingester: IngestionConsumer
let team: Team
beforeAll(async () => {
- clickhouse = Clickhouse.create()
await ensureKafkaTopics(TEST_KAFKA_TOPICS)
- await resetTestDatabase()
- await clickhouse.resetTestDatabase()
- })
-
- afterAll(async () => {
- await resetTestDatabase()
- await clickhouse.resetTestDatabase()
- clickhouse.close()
})
beforeEach(async () => {
@@ -196,7 +185,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
})
kafkaProducer = await KafkaProducerWrapper.create(infra.config.KAFKA_CLIENT_RACK)
- const teamId = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)
+ const teamId = uniqueTestId()
const userId = teamId
const organizationId = new UUIDT().toString()
const userUuid = new UUIDT().toString()
@@ -706,7 +695,7 @@ describe.each(FLAG_COMBINATIONS)('Person Updates E2E ($#)', (config) => {
describe(`${configName} - person_last_seen_at_enabled disabled`, () => {
beforeEach(async () => {
- const disabledTeamId = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)
+ const disabledTeamId = uniqueTestId()
const disabledUserId = disabledTeamId
const disabledUserUuid = new UUIDT().toString()
const disabledOrgId = new UUIDT().toString()
diff --git a/nodejs/tests/ingestion/pipelines/clientwarnings/consumer-e2e.serial.test.ts b/nodejs/tests/ingestion/pipelines/clientwarnings/consumer-e2e.test.ts
similarity index 95%
rename from nodejs/tests/ingestion/pipelines/clientwarnings/consumer-e2e.serial.test.ts
rename to nodejs/tests/ingestion/pipelines/clientwarnings/consumer-e2e.test.ts
index 88ea5afe9803..c6ddaf53d872 100644
--- a/nodejs/tests/ingestion/pipelines/clientwarnings/consumer-e2e.serial.test.ts
+++ b/nodejs/tests/ingestion/pipelines/clientwarnings/consumer-e2e.test.ts
@@ -1,4 +1,3 @@
-// Serial: resets shared Postgres and ClickHouse state and consumes shared Kafka output.
import { Message } from 'node-rdkafka'
import { readFileSync } from 'node:fs'
import path from 'node:path'
@@ -27,7 +26,6 @@ import {
waitForClickHouseKafkaConsumer,
} from '~/tests/helpers/ingestion-e2e'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
-import { resetTestDatabase } from '~/tests/helpers/sql'
type CapturedBatchHandler = (messages: Message[]) => Promise<{ backgroundTask?: Promise<unknown> } | void>
@@ -131,14 +129,10 @@ describe('ClientWarnings consumer E2E', () => {
beforeAll(async () => {
clickhouse = Clickhouse.create()
await ensureKafkaTopics(TEST_KAFKA_TOPICS)
- await resetTestDatabase()
- await clickhouse.resetTestDatabase()
await waitForClickHouseKafkaConsumer(clickhouse)
})
- afterAll(async () => {
- await resetTestDatabase()
- await clickhouse.resetTestDatabase()
+ afterAll(() => {
clickhouse.close()
})
diff --git a/nodejs/tests/ingestion/pipelines/heatmaps/consumer-e2e.serial.test.ts b/nodejs/tests/ingestion/pipelines/heatmaps/consumer-e2e.test.ts
similarity index 94%
rename from nodejs/tests/ingestion/pipelines/heatmaps/consumer-e2e.serial.test.ts
rename to nodejs/tests/ingestion/pipelines/heatmaps/consumer-e2e.test.ts
index f59e30fc6097..69879e6a5468 100644
--- a/nodejs/tests/ingestion/pipelines/heatmaps/consumer-e2e.serial.test.ts
+++ b/nodejs/tests/ingestion/pipelines/heatmaps/consumer-e2e.test.ts
@@ -1,4 +1,3 @@
-// Serial: resets shared Postgres and ClickHouse state and consumes shared Kafka output.
import { Message } from 'node-rdkafka'
import { CookielessManagerComponent } from '~/ingestion/common/cookieless/cookieless-manager'
@@ -24,7 +23,6 @@ import {
waitForClickHouseKafkaConsumer,
} from '~/tests/helpers/ingestion-e2e'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
-import { resetTestDatabase } from '~/tests/helpers/sql'
type CapturedBatchHandler = (messages: Message[]) => Promise<{ backgroundTask?: Promise<unknown> } | void>
@@ -122,14 +120,10 @@ describe('Heatmaps consumer E2E', () => {
beforeAll(async () => {
clickhouse = Clickhouse.create()
await ensureKafkaTopics(TEST_KAFKA_TOPICS)
- await resetTestDatabase()
- await clickhouse.resetTestDatabase()
await waitForClickHouseKafkaConsumer(clickhouse)
})
- afterAll(async () => {
- await resetTestDatabase()
- await clickhouse.resetTestDatabase()
+ afterAll(() => {
clickhouse.close()
})
diff --git a/nodejs/tests/ingestion/pipelines/sessionreplay/__snapshots__/consumer.e2e.serial.test.ts.snap b/nodejs/tests/ingestion/pipelines/sessionreplay/__snapshots__/consumer.e2e.test.ts.snap
similarity index 100%
rename from nodejs/tests/ingestion/pipelines/sessionreplay/__snapshots__/consumer.e2e.serial.test.ts.snap
rename to nodejs/tests/ingestion/pipelines/sessionreplay/__snapshots__/consumer.e2e.test.ts.snap
diff --git a/nodejs/tests/ingestion/pipelines/sessionreplay/consumer.e2e.serial.test.ts b/nodejs/tests/ingestion/pipelines/sessionreplay/consumer.e2e.test.ts
similarity index 98%
rename from nodejs/tests/ingestion/pipelines/sessionreplay/consumer.e2e.serial.test.ts
rename to nodejs/tests/ingestion/pipelines/sessionreplay/consumer.e2e.test.ts
index 0ebdbd1bcb27..9408ab6bcf25 100644
--- a/nodejs/tests/ingestion/pipelines/sessionreplay/consumer.e2e.serial.test.ts
+++ b/nodejs/tests/ingestion/pipelines/sessionreplay/consumer.e2e.test.ts
@@ -36,7 +36,7 @@ import { waitForExpect } from '~/tests/helpers/expectations'
import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
import { forSnapshot } from '~/tests/helpers/snapshots'
-import { createOrganization, createTeam, getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
+import { createOrganization, createTeam, createTestTeamFixture } from '~/tests/helpers/sql'
import { Team } from '~/types'
// Test configuration - matches local dev environment (MinIO API on port 19000)
@@ -53,9 +53,9 @@ const TEST_CONFIG = {
// Reduced wait time for partition assignments (1 second is usually enough locally)
const PARTITION_ASSIGNMENT_WAIT_MS = 1000
-// Token for a team that has DROP_EVENT restriction applied
-// This team is created in beforeAll and the restriction is set in Redis
-const RESTRICTED_TEAM_TOKEN = 'restricted-team-token-for-e2e-tests'
+// Token for a team that has DROP_EVENT restriction applied. Assigned in beforeAll,
+// so the rows it leaves behind never collide with an earlier run's.
+let RESTRICTED_TEAM_TOKEN = ''
/**
* Payload configuration for test cases.
@@ -956,7 +956,6 @@ describe('Session Recording Consumer Integration', () => {
}
await ensureKafkaTopics(TEST_KAFKA_TOPICS)
- await resetTestDatabase()
infra = await createIngestionTestInfra({
SESSION_RECORDING_V2_S3_BUCKET: TEST_CONFIG.S3_BUCKET,
@@ -970,17 +969,10 @@ describe('Session Recording Consumer Integration', () => {
SESSION_RECORDING_MAX_BATCH_AGE_MS: 1000,
})
- team = await getFirstTeam(infra.postgres)
-
- // Enable console log capture for the primary team so console log tests work
- await infra.postgres.query(
- PostgresUse.COMMON_WRITE,
- 'UPDATE posthog_team SET capture_console_log_opt_in = true WHERE id = $1',
- [team.id],
- 'enable-console-log-capture'
- )
+ team = (await createTestTeamFixture(infra.postgres, { capture_console_log_opt_in: true })).team
// Create a second team with a known token that will have DROP_EVENT restriction
+ RESTRICTED_TEAM_TOKEN = `restricted-team-${uuidv4()}`
const restrictedOrgId = await createOrganization(infra.postgres)
await createTeam(infra.postgres, restrictedOrgId, RESTRICTED_TEAM_TOKEN)
diff --git a/nodejs/tests/ingestion/postgres-parity.test.ts b/nodejs/tests/ingestion/postgres-parity.test.ts
index 4563e66f92c5..2294e48e1a60 100644
--- a/nodejs/tests/ingestion/postgres-parity.test.ts
+++ b/nodejs/tests/ingestion/postgres-parity.test.ts
@@ -21,7 +21,7 @@ import { PluginServerMode, PluginsServerConfig, PropertyUpdateOperation, Timesta
import { Clickhouse } from '../helpers/clickhouse'
import { waitForExpect } from '../helpers/expectations'
import { ensureKafkaTopics } from '../helpers/kafka'
-import { createUserTeamAndOrganization } from '../helpers/sql'
+import { createUserTeamAndOrganization, uniqueTestId } from '../helpers/sql'
jest.mock('~/common/utils/logger')
@@ -114,7 +114,7 @@ describe('postgres parity', () => {
// tables, which is redundant (unique teamId already isolates) and harmful
// (all 3 CI shards share the same DB, so global truncation corrupts
// in-flight state in other shards).
- teamId = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)
+ teamId = uniqueTestId()
server = new IngestionGeneralServer({
PLUGIN_SERVER_MODE: PluginServerMode.ingestion_v2,