:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ingestion): stop rewriting the team row after the first event (#88662)
Danieldf69f085f811
diff --git a/nodejs/src/common/utils/team-manager.test.ts b/nodejs/src/common/utils/team-manager.test.tsindex 5f1bfe6c6106..840d7250ab16 100644--- a/nodejs/src/common/utils/team-manager.test.ts+++ b/nodejs/src/common/utils/team-manager.test.ts@@ -10,9 +10,16 @@ import { Hub, Team } from '~/types'import { defaultConfig } from '../config/config'import { closeHub, createHub } from './db/hub'-import { PostgresRouter } from './db/postgres'+import { PostgresRouter, PostgresUse } from './db/postgres'+import { captureTeamEvent } from './posthog'import { TeamManager } from './team-manager'+jest.mock('~/common/utils/posthog', () => ({+ captureTeamEvent: jest.fn(),+}))++const mockCaptureTeamEvent = captureTeamEvent as jest.Mock+describe('TeamManager()', () => {let hub: Hublet teamManager: TeamManager@@ -262,4 +269,81 @@ describe('TeamManager()', () => {expect(result).toBe(true)})})++ describe('setTeamIngestedEvent()', () => {+ const newTeamToken = 'token-for-a-team-with-no-events-yet'+ let newTeam: Team++ const readIngestedEvent = async (id: Team['id']): Promise<boolean> => {+ const result = await postgres.query<{ ingested_event: boolean }>(+ PostgresUse.COMMON_READ,+ 'SELECT ingested_event FROM posthog_team WHERE id = $1',+ [id],+ 'test-read-ingested-event'+ )+ return result.rows[0].ingested_event+ }++ beforeEach(async () => {+ await createTeam(postgres, organizationId, newTeamToken, { ingested_event: false })+ const loaded = await teamManager.getTeamByToken(newTeamToken)+ expect(loaded?.ingested_event).toBe(false)+ newTeam = loaded as Team+ })++ it('flips the flag and captures the first event for each org member', async () => {+ await teamManager.setTeamIngestedEvent(newTeam, { $lib: 'web' })++ expect(await readIngestedEvent(newTeam.id)).toBe(true)+ expect(mockCaptureTeamEvent).toHaveBeenCalledTimes(1)+ expect(mockCaptureTeamEvent).toHaveBeenCalledWith(+ newTeam,+ 'first team event ingested',+ expect.objectContaining({ sdk: 'web' }),+ expect.any(String)+ )+ })++ it('does nothing on a repeat call through a stale team object', async () => {+ await teamManager.setTeamIngestedEvent(newTeam, { $lib: 'web' })+ mockCaptureTeamEvent.mockClear()++ // `newTeam` still reads ingested_event=false, which is the stale-cache case exactly.+ await teamManager.setTeamIngestedEvent(newTeam, { $lib: 'web' })++ expect(mockCaptureTeamEvent).not.toHaveBeenCalled()+ expect(await readIngestedEvent(newTeam.id)).toBe(true)+ })++ it('captures exactly once when two workers race on the same new team', async () => {+ await Promise.all([+ teamManager.setTeamIngestedEvent(newTeam, { $lib: 'web' }),+ teamManager.setTeamIngestedEvent({ ...newTeam }, { $lib: 'web' }),+ ])++ expect(mockCaptureTeamEvent).toHaveBeenCalledTimes(1)+ expect(await readIngestedEvent(newTeam.id)).toBe(true)+ })++ it('refreshes the token cache entry so the next lookup sees the flag', async () => {+ await teamManager.setTeamIngestedEvent(newTeam, { $lib: 'web' })+ fetchTeamsSpy.mockClear()++ // Ingestion only ever looks teams up by token, so the token entry is the one that has+ // to be invalidated. `Date.now` is frozen here, so nothing else can expire it.+ const reloaded = await teamManager.getTeamByToken(newTeamToken)++ expect(fetchTeamsSpy).toHaveBeenCalledTimes(1)+ expect(reloaded?.ingested_event).toBe(true)+ })++ it('issues no query at all for a team already flagged as ingested', async () => {+ const querySpy = jest.spyOn(postgres, 'query')++ await teamManager.setTeamIngestedEvent({ ...newTeam, ingested_event: true }, { $lib: 'web' })++ expect(querySpy).not.toHaveBeenCalled()+ expect(mockCaptureTeamEvent).not.toHaveBeenCalled()+ })+ })})diff --git a/nodejs/src/common/utils/team-manager.ts b/nodejs/src/common/utils/team-manager.tsindex e95583eecf34..f6d85854918f 100644--- a/nodejs/src/common/utils/team-manager.ts+++ b/nodejs/src/common/utils/team-manager.ts@@ -3,6 +3,7 @@ import { OrganizationAvailableFeature, ProjectId, Team } from '~/types'import { PostgresRouter, PostgresUse } from './db/postgres'import { LazyLoader, LoaderRetryOptions } from './lazy-loader'+import { logger } from './logger'import { captureTeamEvent } from './posthog'type RawTeam = Omit<Team, 'available_features'> & {@@ -60,35 +61,51 @@ export class TeamManager {public async setTeamIngestedEvent(team: Team, properties: Properties): Promise<void> {if (!team.ingested_event) {- await this.postgres.query(+ // The cached team can be stale long after the first write, so this fires repeatedly for+ // a team that is already flagged. The guard makes those repeats match zero rows, which+ // writes nothing and leaves no dead tuple behind on a hot row.+ const updateResult = await this.postgres.query(PostgresUse.COMMON_WRITE,- `UPDATE posthog_team SET ingested_event = $1 WHERE id = $2`,+ `UPDATE posthog_team SET ingested_event = $1 WHERE id = $2 AND NOT ingested_event`,[true, team.id],'setTeamIngestedEvent')- // Invalidate the cache for this team- this.lazyLoader.markForRefresh(String(team.id))+ // Both keys, because a team is cached under its id and its token but ingestion only ever+ // looks it up by token - refreshing the id alone leaves the entry this worker reads stale.+ this.lazyLoader.markForRefresh([String(team.id), team.api_token])- const organizationMembers = await this.postgres.query(- PostgresUse.COMMON_WRITE,- 'SELECT distinct_id FROM posthog_user JOIN posthog_organizationmembership ON posthog_user.id = posthog_organizationmembership.user_id WHERE organization_id = $1',- [team.organization_id],- 'posthog_organizationmembership'- )+ if ((updateResult.rowCount ?? 0) === 0) {+ // Another worker (or an earlier event seen through a stale cache) already flipped+ // the flag - skip the first-event side effects so they fire exactly once per team.+ return+ }- const distinctIds: { distinct_id: string }[] = organizationMembers.rows- for (const { distinct_id } of distinctIds) {- captureTeamEvent(- team,- 'first team event ingested',- {- sdk: properties.$lib,- realm: properties.realm,- host: properties.$host,- },- distinct_id+ // The flag is already committed and no later event retries these, so a throw here loses+ // the team's first-event capture for good. Swallow it and leave a trail instead.+ try {+ const organizationMembers = await this.postgres.query(+ PostgresUse.COMMON_WRITE,+ 'SELECT distinct_id FROM posthog_user JOIN posthog_organizationmembership ON posthog_user.id = posthog_organizationmembership.user_id WHERE organization_id = $1',+ [team.organization_id],+ 'posthog_organizationmembership')++ const distinctIds: { distinct_id: string }[] = organizationMembers.rows+ for (const { distinct_id } of distinctIds) {+ captureTeamEvent(+ team,+ 'first team event ingested',+ {+ sdk: properties.$lib,+ realm: properties.realm,+ host: properties.$host,+ },+ distinct_id+ )+ }+ } catch (error) {+ logger.error('⚠️', 'Failed to capture first team event ingested', { teamId: team.id, error })}}}