:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): emit an event when a team's email reputation state changes (#74558)
Meikel Ratzb1b22fee4747
diff --git a/nodejs/src/cdp/services/email-reputation/email-reputation.service.test.ts b/nodejs/src/cdp/services/email-reputation/email-reputation.service.test.tsindex 344b3f702ac2..aa7dc033a6bb 100644--- a/nodejs/src/cdp/services/email-reputation/email-reputation.service.test.ts+++ b/nodejs/src/cdp/services/email-reputation/email-reputation.service.test.ts@@ -5,6 +5,8 @@ import { insertHogFlow } from '~/cdp/_tests/fixtures-hogflows'import { HogFlow } from '~/cdp/schema/hogflow'import { closeHub, createHub } from '~/common/utils/db/hub'import { PostgresUse } from '~/common/utils/db/postgres'+import { captureTeamEvent } from '~/common/utils/posthog'+import { TeamManager } from '~/common/utils/team-manager'import { createTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'import { Hub } from '~/types'@@ -12,6 +14,12 @@ import { DEFAULT_THRESHOLDS, ReputationMetrics } from './classifier'import { EmailReputationService, representativeVolume } from './email-reputation.service'import { HourlyEmailMetricsRow } from './types'+jest.mock('~/common/utils/posthog', () => ({+ ...jest.requireActual('~/common/utils/posthog'),+ captureTeamEvent: jest.fn(),+}))+const mockCaptureTeamEvent = captureTeamEvent as jest.Mock+const EVALUATED_AT = '2026-07-10T06:00:00.000Z'const HOURS_AGO = (hours: number): number => Math.floor(Date.parse(EVALUATED_AT) / 1000) - hours * 3600@@ -88,9 +96,10 @@ describe('EmailReputationService', () => {const team = await getTeam(hub.postgres, 2)teamId = await createTeam(hub.postgres, team!.organization_id)mockClickhouse = { query: jest.fn() }+ mockCaptureTeamEvent.mockClear()// multiplier 1 keeps these tests pinning the pure window-walk mechanics (representative// volume = the fixed target); the multiplier's own sizing behavior has its own block below.- service = new EmailReputationService(mockClickhouse as any, hub.postgres, {+ service = new EmailReputationService(mockClickhouse as any, hub.postgres, new TeamManager(hub.postgres), {targetVolume: 1000,minWindowHours: 24,lookbackDays: 30,@@ -297,13 +306,18 @@ describe('EmailReputationService', () => {let scaledService: EmailReputationServicebeforeEach(() => {- scaledService = new EmailReputationService(mockClickhouse as any, hub.postgres, {- targetVolume: 1000,- minWindowHours: 24,- lookbackDays: 30,- representativeVolumeMultiplier: 3,- thresholds: DEFAULT_THRESHOLDS,- })+ scaledService = new EmailReputationService(+ mockClickhouse as any,+ hub.postgres,+ new TeamManager(hub.postgres),+ {+ targetVolume: 1000,+ minWindowHours: 24,+ lookbackDays: 30,+ representativeVolumeMultiplier: 3,+ thresholds: DEFAULT_THRESHOLDS,+ }+ )})it('one clean campaign cannot wash out yesterday`s disaster', async () => {@@ -344,4 +358,79 @@ describe('EmailReputationService', () => {expect(teamRow.bounce_rate).toBeCloseTo(0.03)})})++ describe('team state change events', () => {+ const criticalMetrics = (flowId: string): HourlyEmailMetricsRow[] => [+ { teamId, appSourceId: flowId, hourBucket: HOURS_AGO(2), sent: 1000, bounced: 60, complained: 0 },+ ]+ const healthyMetrics = (flowId: string): HourlyEmailMetricsRow[] => [+ { teamId, appSourceId: flowId, hourBucket: HOURS_AGO(2), sent: 1000, bounced: 1, complained: 0 },+ ]++ it('emits on entering critical, with retries emitting nothing extra', async () => {+ const flow = await insertEmailFlow()+ mockMetrics(criticalMetrics(flow.id))++ await service.evaluateTeamBatch([teamId], EVALUATED_AT)++ expect(mockCaptureTeamEvent).toHaveBeenCalledTimes(1)+ const [team, event, properties] = mockCaptureTeamEvent.mock.calls[0]+ expect(team.id).toEqual(teamId)+ expect(event).toEqual('workflow_email_reputation_state_changed')+ expect(properties).toMatchObject({+ scope: 'team',+ affected_team_id: teamId,+ previous_state: null,+ new_state: 'critical',+ emails_sent: 1000,+ email_sending_suspended: false,+ })++ // A retried Temporal activity re-runs the batch; the ON CONFLICT dedupe must gate the emit too+ await service.evaluateTeamBatch([teamId], EVALUATED_AT)+ expect(mockCaptureTeamEvent).toHaveBeenCalledTimes(1)+ })++ it('emits a repeat every run while critical, carrying the suspension flag', async () => {+ const flow = await insertEmailFlow()+ mockMetrics(criticalMetrics(flow.id))+ await service.evaluateTeamBatch([teamId], EVALUATED_AT)++ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO workflows_teamworkflowsconfig (team_id, capture_workflows_engagement_events, email_tracking_consent_mode, email_sending_suspended_at, email_sending_suspension_reason)+ VALUES ($1, false, 'off', now(), 'test') `,+ [teamId],+ 'testSuspendTeam'+ )+ await service.evaluateTeamBatch([teamId], '2026-07-11T06:00:00.000Z')++ expect(mockCaptureTeamEvent).toHaveBeenCalledTimes(2)+ expect(mockCaptureTeamEvent.mock.calls[1][2]).toMatchObject({+ previous_state: 'critical',+ new_state: 'critical',+ email_sending_suspended: true,+ })+ })++ it('emits the recovery transition but stays silent for always-healthy teams', async () => {+ const flow = await insertEmailFlow()+ mockMetrics(healthyMetrics(flow.id))+ await service.evaluateTeamBatch([teamId], EVALUATED_AT)+ // First evaluation landing on healthy is not an event+ expect(mockCaptureTeamEvent).not.toHaveBeenCalled()++ mockMetrics(criticalMetrics(flow.id))+ await service.evaluateTeamBatch([teamId], '2026-07-11T06:00:00.000Z')+ mockMetrics(healthyMetrics(flow.id))+ await service.evaluateTeamBatch([teamId], '2026-07-12T06:00:00.000Z')++ expect(mockCaptureTeamEvent).toHaveBeenCalledTimes(2)+ expect(mockCaptureTeamEvent.mock.calls[1][2]).toMatchObject({+ previous_state: 'critical',+ new_state: 'healthy',+ email_sending_suspended: false,+ })+ })+ })})diff --git a/nodejs/src/cdp/services/email-reputation/email-reputation.service.ts b/nodejs/src/cdp/services/email-reputation/email-reputation.service.tsindex ba5b19750a2c..b20ccafb8b77 100644--- a/nodejs/src/cdp/services/email-reputation/email-reputation.service.ts+++ b/nodejs/src/cdp/services/email-reputation/email-reputation.service.ts@@ -4,10 +4,16 @@ import { Counter } from 'prom-client'import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'import { logger } from '~/common/utils/logger'+import { captureTeamEvent } from '~/common/utils/posthog'+import { TeamManager } from '~/common/utils/team-manager'import { ReputationMetrics, ReputationThresholds, classifyReputation } from './classifier'import { BatchEvaluationSummary, HourlyEmailMetricsRow } from './types'+export const REPUTATION_STATE_CHANGED_EVENT = 'workflow_email_reputation_state_changed'++const DEGRADED_STATES = new Set(['warning', 'critical'])+const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iconst reputationSnapshotsCounter = new Counter({@@ -72,6 +78,7 @@ export class EmailReputationService {constructor(private clickhouse: ClickHouseClient,private postgres: PostgresRouter,+ private teamManager: TeamManager,private config: EmailReputationServiceConfig) {}@@ -216,11 +223,20 @@ export class EmailReputationService {summary.teamsEvaluated++}+ // Read before the inserts so "previous" can't see this run's own rows.+ const previousStates = await this.fetchPreviousTeamStates(teamIds, evaluatedAt)+ const suspendedTeamIds = await this.fetchSuspendedTeamIds(teamIds)+for (const snapshot of snapshots) {const inserted = await this.insertSnapshot(snapshot, evaluatedAt)if (inserted) {summary.snapshotsWritten++reputationSnapshotsCounter.labels(snapshot.scope, snapshot.state).inc()+ if (snapshot.scope === 'team') {+ // Emitting only on a real insert makes Temporal activity retries emit-once for+ // free: a retried batch hits ON CONFLICT and never reaches this branch.+ await this.maybeEmitTeamStateChange(snapshot, previousStates, suspendedTeamIds, evaluatedAt)+ }}}@@ -349,6 +365,76 @@ export class EmailReputationService {return representativeVolume(buckets, this.config.targetVolume, this.config.representativeVolumeMultiplier)}+ /**+ * Emit `workflow_email_reputation_state_changed` into PostHog's own project for team-scope+ * snapshots, so internal alerting/analytics ride the CDP (a workflow with a Slack destination+ * consumes it) instead of a hardcoded webhook. Emits on any transition into or out of a+ * degraded state, and on every run while critical — the repeat while critical and unsuspended+ * is the manual enforcement queue's nag; the consumer filters on `email_sending_suspended`.+ * Quietly-healthy fleets emit nothing (a new team's first healthy snapshot is not an event).+ */+ private async maybeEmitTeamStateChange(+ snapshot: SnapshotRow,+ previousStates: Map<number, string>,+ suspendedTeamIds: Set<number>,+ evaluatedAt: string+ ): Promise<void> {+ const previousState = previousStates.get(snapshot.teamId) ?? null+ const changed = previousState !== snapshot.state+ const involvesDegraded =+ DEGRADED_STATES.has(snapshot.state) || (previousState !== null && DEGRADED_STATES.has(previousState))+ if (!((changed && involvesDegraded) || snapshot.state === 'critical')) {+ return+ }+ try {+ const team = await this.teamManager.getTeam(snapshot.teamId)+ if (!team) {+ return+ }+ captureTeamEvent(team, REPUTATION_STATE_CHANGED_EVENT, {+ scope: 'team',+ affected_team_id: snapshot.teamId,+ previous_state: previousState,+ new_state: snapshot.state,+ bounce_rate: snapshot.bounceRate,+ complaint_rate: snapshot.complaintRate,+ emails_sent: snapshot.emailsSent,+ evaluated_at: evaluatedAt,+ email_sending_suspended: suspendedTeamIds.has(snapshot.teamId),+ })+ } catch (error) {+ // The snapshot is the source of truth; a failed emit must not fail the batch.+ logger.error('[EmailReputation] failed to emit state change event', {+ teamId: snapshot.teamId,+ error,+ })+ }+ }++ private async fetchPreviousTeamStates(teamIds: number[], evaluatedAt: string): Promise<Map<number, string>> {+ const result = await this.postgres.query<{ team_id: number | string; state: string }>(+ PostgresUse.COMMON_READ,+ `SELECT DISTINCT ON (team_id) team_id, state+ FROM posthog_emailreputationsnapshot+ WHERE hog_flow_id IS NULL AND team_id = ANY($1) AND evaluated_at < $2::timestamptz+ ORDER BY team_id, evaluated_at DESC`,+ [teamIds, evaluatedAt],+ 'emailReputationFetchPreviousTeamStates'+ )+ return new Map(result.rows.map((row) => [Number(row.team_id), row.state]))+ }++ private async fetchSuspendedTeamIds(teamIds: number[]): Promise<Set<number>> {+ const result = await this.postgres.query<{ team_id: number | string }>(+ PostgresUse.COMMON_READ,+ `SELECT team_id FROM workflows_teamworkflowsconfig+ WHERE team_id = ANY($1) AND email_sending_suspended_at IS NOT NULL`,+ [teamIds],+ 'emailReputationFetchSuspendedTeams'+ )+ return new Set(result.rows.map((row) => Number(row.team_id)))+ }+/** Returns true if a row was written, false if it already existed (retry dedupe). */private async insertSnapshot(snapshot: SnapshotRow, evaluatedAt: string): Promise<boolean> {const result = await this.postgres.query(diff --git a/nodejs/src/cdp/services/email-reputation/temporal/email-reputation-worker.service.ts b/nodejs/src/cdp/services/email-reputation/temporal/email-reputation-worker.service.tsindex a7b1c8604c91..ee8e106bb7e6 100644--- a/nodejs/src/cdp/services/email-reputation/temporal/email-reputation-worker.service.ts+++ b/nodejs/src/cdp/services/email-reputation/temporal/email-reputation-worker.service.ts@@ -8,6 +8,7 @@ import https from 'https'import { EncryptionCodec } from '~/common/temporal/codec'import { PostgresRouter } from '~/common/utils/db/postgres'import { logger } from '~/common/utils/logger'+import { TeamManager } from '~/common/utils/team-manager'import {HealthCheckResult,HealthCheckResultError,@@ -95,7 +96,7 @@ export class EmailReputationWorkerService {}: {}),})- return new EmailReputationService(clickhouse, this.deps.postgres, {+ return new EmailReputationService(clickhouse, this.deps.postgres, new TeamManager(this.deps.postgres), {targetVolume: this.config.EMAIL_REPUTATION_TARGET_VOLUME,minWindowHours: this.config.EMAIL_REPUTATION_MIN_WINDOW_HOURS,lookbackDays: this.config.EMAIL_REPUTATION_LOOKBACK_DAYS,