: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
chore(workflows): remove the email reputation evaluator (#74743)
Meikel Ratzd24a844e95d6
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.tsindex 9ac7c4e835a0..deca0e1ef3e1 100644--- a/nodejs/src/capabilities.ts+++ b/nodejs/src/capabilities.ts@@ -30,7 +30,6 @@ export const CAPABILITIES_CDP_WORKFLOWS: PluginServerCapabilities = {cdpCyclotronV2Janitor: isDevEnv(),cdpHogflowScheduler: isDevEnv(),cdpHogflowSubscriptionMatcher: isDevEnv(),- emailReputationEvaluator: isDevEnv(),}/** Realtime Cohorts - precalculated filters and cohort membership */@@ -200,10 +199,6 @@ export function getPluginServerCapabilities(return {cdpHogflowScheduler: true,}- case PluginServerMode.email_reputation_evaluator:- return {- emailReputationEvaluator: true,- }case PluginServerMode.recordings_blob_ingestion_v2:case PluginServerMode.recordings_blob_ingestion_v2_overflow:case PluginServerMode.recordings_blob_ingestion_v2_ml_mirror:diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 30716427c6a1..4a52343122fa 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -18,7 +18,6 @@ import {WARPSTREAM_CYCLOTRON_PRODUCER,WARPSTREAM_INGESTION_PRODUCER,} from './outputs/producers'-import { DEFAULT_THRESHOLDS } from './services/email-reputation/classifier'import { CyclotronJobQueueKind, CyclotronJobQueueSource } from './types'// CdpConfig intersects ClickhouseConfig so any consumer reading@@ -184,18 +183,6 @@ export type CdpConfig = ClickhouseConfig & {CYCLOTRON_NODE_RESCHEDULE_CHUNK_SLEEP_MS: number// Email reputation evaluator (daily Temporal-scheduled bounce/complaint snapshots for workflows email)- EMAIL_REPUTATION_EVALUATION_HOUR_UTC: number- EMAIL_REPUTATION_TARGET_VOLUME: number- EMAIL_REPUTATION_VOLUME_MULTIPLIER: number- EMAIL_REPUTATION_MIN_WINDOW_HOURS: number- EMAIL_REPUTATION_LOOKBACK_DAYS: number- EMAIL_REPUTATION_MIN_SENDS: number- EMAIL_REPUTATION_BOUNCE_WARNING_RATE: number- EMAIL_REPUTATION_BOUNCE_CRITICAL_RATE: number- EMAIL_REPUTATION_COMPLAINT_WARNING_RATE: number- EMAIL_REPUTATION_COMPLAINT_CRITICAL_RATE: number- EMAIL_REPUTATION_BATCH_SIZE: number- EMAIL_REPUTATION_BATCH_DELAY_SECONDS: number}export function getDefaultCdpConfig(): CdpConfig {@@ -353,24 +340,5 @@ export function getDefaultCdpConfig(): CdpConfig {CYCLOTRON_NODE_RESCHEDULE_CHUNK_SIZE: 5000,CYCLOTRON_NODE_RESCHEDULE_MAX_CHUNKS_PER_CALL: 20,CYCLOTRON_NODE_RESCHEDULE_CHUNK_SLEEP_MS: 100,-- // Thresholds sit ahead of AWS SES's review lines (5% bounce / 0.1% complaint at ~0.5%- // escalation). Rates are computed SES-style over a window spanning at least- // MIN_WINDOW_HOURS and at least the target's representative volume of sends —- // max(TARGET_VOLUME, VOLUME_MULTIPLIER × its biggest sending day) — whichever reaches- // further back (capped at LOOKBACK_DAYS). Calculation only for now — enforcement- // ships separately.- EMAIL_REPUTATION_EVALUATION_HOUR_UTC: 6,- EMAIL_REPUTATION_TARGET_VOLUME: 1000,- EMAIL_REPUTATION_VOLUME_MULTIPLIER: 3,- EMAIL_REPUTATION_MIN_WINDOW_HOURS: 24,- EMAIL_REPUTATION_LOOKBACK_DAYS: 30,- EMAIL_REPUTATION_MIN_SENDS: DEFAULT_THRESHOLDS.minSends,- EMAIL_REPUTATION_BOUNCE_WARNING_RATE: DEFAULT_THRESHOLDS.bounceWarning,- EMAIL_REPUTATION_BOUNCE_CRITICAL_RATE: DEFAULT_THRESHOLDS.bounceCritical,- EMAIL_REPUTATION_COMPLAINT_WARNING_RATE: DEFAULT_THRESHOLDS.complaintWarning,- EMAIL_REPUTATION_COMPLAINT_CRITICAL_RATE: DEFAULT_THRESHOLDS.complaintCritical,- EMAIL_REPUTATION_BATCH_SIZE: 50,- EMAIL_REPUTATION_BATCH_DELAY_SECONDS: 30,}}diff --git a/nodejs/src/cdp/services/email-reputation/classifier.test.ts b/nodejs/src/cdp/services/email-reputation/classifier.test.tsdeleted file mode 100644index cdcb917aa73e..000000000000--- a/nodejs/src/cdp/services/email-reputation/classifier.test.ts+++ /dev/null@@ -1,30 +0,0 @@-import { ReputationMetrics, ReputationState, classifyReputation } from './classifier'--describe('classifyReputation', () => {- it.each<[string, ReputationMetrics, ReputationState]>([- ['zero sends is insufficient data', { sent: 0, bounced: 0, complained: 0 }, 'insufficient_data'],- [- 'below min sends is insufficient data even at terrible rates',- { sent: 50, bounced: 25, complained: 5 },- 'insufficient_data',- ],- ['healthy below all thresholds', { sent: 1000, bounced: 5, complained: 0 }, 'healthy'],- ['warning at the bounce warning threshold (inclusive)', { sent: 1000, bounced: 20, complained: 0 }, 'warning'],- [- 'warning at the complaint warning threshold (inclusive)',- { sent: 1000, bounced: 0, complained: 1 },- 'warning',- ],- ['critical at the bounce critical threshold', { sent: 1000, bounced: 50, complained: 0 }, 'critical'],- ['critical at the complaint critical threshold', { sent: 1000, bounced: 0, complained: 5 }, 'critical'],- ['critical wins over warning when signals disagree', { sent: 1000, bounced: 20, complained: 5 }, 'critical'],- ])('%s', (_name, metrics, expected) => {- expect(classifyReputation(metrics).state).toEqual(expected)- })-- it('reports the computed rates', () => {- const { bounceRate, complaintRate } = classifyReputation({ sent: 200, bounced: 10, complained: 1 })- expect(bounceRate).toBeCloseTo(0.05)- expect(complaintRate).toBeCloseTo(0.005)- })-})diff --git a/nodejs/src/cdp/services/email-reputation/classifier.ts b/nodejs/src/cdp/services/email-reputation/classifier.tsdeleted file mode 100644index 4df0e926e6e4..000000000000--- a/nodejs/src/cdp/services/email-reputation/classifier.ts+++ /dev/null@@ -1,64 +0,0 @@-/**- * Pure classifier for email sender reputation, evaluated per workflow and per team.- *- * Each daily evaluation classifies the window's bounce/complaint rates against fixed- * thresholds — there are no transitions or sticky states; every run recomputes from scratch.- * Values mirror `posthog_emailreputationsnapshot.state`:- * - insufficient_data: too few sends in the window to judge the rates- * - healthy: below all warning thresholds- * - warning: over a warning threshold- * - critical: over a critical threshold (the level that will drive pausing once enforcement ships)- */--export type ReputationState = 'insufficient_data' | 'healthy' | 'warning' | 'critical'--export interface ReputationThresholds {- /** Below this many sends in the window, rates are too noisy to judge. */- minSends: number- bounceWarning: number- bounceCritical: number- complaintWarning: number- complaintCritical: number-}--// Warn well before AWS's account-review lines (5% bounce / 0.1% complaint at ~0.5% escalation).-export const DEFAULT_THRESHOLDS: ReputationThresholds = {- minSends: 100,- bounceWarning: 0.02,- bounceCritical: 0.05,- complaintWarning: 0.001,- complaintCritical: 0.005,-}--export interface ReputationMetrics {- sent: number- bounced: number- complained: number-}--export interface ReputationClassification {- state: ReputationState- bounceRate: number- complaintRate: number-}--export function classifyReputation(- metrics: ReputationMetrics,- thresholds: ReputationThresholds = DEFAULT_THRESHOLDS-): ReputationClassification {- const bounceRate = metrics.sent > 0 ? metrics.bounced / metrics.sent : 0- const complaintRate = metrics.sent > 0 ? metrics.complained / metrics.sent : 0-- let state: ReputationState- if (metrics.sent < thresholds.minSends) {- state = 'insufficient_data'- } else if (complaintRate >= thresholds.complaintCritical || bounceRate >= thresholds.bounceCritical) {- state = 'critical'- } else if (complaintRate >= thresholds.complaintWarning || bounceRate >= thresholds.bounceWarning) {- state = 'warning'- } else {- state = 'healthy'- }-- return { state, bounceRate, complaintRate }-}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.tsdeleted file mode 100644index aa7dc033a6bb..000000000000--- a/nodejs/src/cdp/services/email-reputation/email-reputation.service.test.ts+++ /dev/null@@ -1,436 +0,0 @@-import { randomUUID } from 'crypto'--import { FixtureHogFlowBuilder } from '~/cdp/_tests/builders/hogflow.builder'-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'--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--describe('EmailReputationService', () => {- jest.setTimeout(5000)-- let hub: Hub- let service: EmailReputationService- let mockClickhouse: { query: jest.Mock }- let teamId: number-- const insertEmailFlow = async (): Promise<HogFlow> => {- return await insertHogFlow(- hub.postgres,- new FixtureHogFlowBuilder()- .withTeamId(teamId)- .withStatus('active')- .withWorkflow({- actions: {- trigger: { type: 'trigger', config: { type: 'event', filters: {} } },- send_email: { type: 'function_email', config: { template_id: 'template-email' } } as any,- exit: { type: 'exit', config: {} },- },- edges: [- { from: 'trigger', to: 'send_email', type: 'continue' },- { from: 'send_email', to: 'exit', type: 'continue' },- ],- })- .build()- )- }-- const insertBatchJob = async (hogFlowId: string): Promise<string> => {- const batchJobId = randomUUID()- await hub.postgres.query(- PostgresUse.COMMON_WRITE,- `INSERT INTO workflows_hogflowbatchjob (id, team_id, hog_flow_id, variables, filters, status, created_at, updated_at)- VALUES ($1, $2, $3, '{}', '{}', 'completed', now(), now())`,- [batchJobId, teamId, hogFlowId],- 'testInsertBatchJob'- )- return batchJobId- }-- const mockMetrics = (rows: HourlyEmailMetricsRow[]): void => {- mockClickhouse.query.mockResolvedValue({- json: () =>- Promise.resolve(- rows.map((row) => ({- team_id: row.teamId,- app_source_id: row.appSourceId,- hour_bucket: row.hourBucket,- sent: row.sent,- bounced: row.bounced,- complained: row.complained,- }))- ),- })- }-- const getSnapshots = async (): Promise<any[]> => {- const result = await hub.postgres.query(- PostgresUse.COMMON_READ,- `SELECT * FROM posthog_emailreputationsnapshot WHERE team_id = $1 ORDER BY scope, hog_flow_id, evaluated_at`,- [teamId],- 'testGetSnapshots'- )- return result.rows- }-- beforeEach(async () => {- hub = await createHub()- await resetTestDatabase()- 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, new TeamManager(hub.postgres), {- targetVolume: 1000,- minWindowHours: 24,- lookbackDays: 30,- representativeVolumeMultiplier: 1,- thresholds: DEFAULT_THRESHOLDS,- })- })-- afterEach(async () => {- await closeHub(hub)- })-- it('writes workflow and team snapshots, and a retried batch adds no duplicate rows', async () => {- const flow = await insertEmailFlow()- mockMetrics([- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(2), sent: 1000, bounced: 60, complained: 0 },- ])-- const summary = await service.evaluateTeamBatch([teamId], EVALUATED_AT)- expect(summary).toMatchObject({ teamsEvaluated: 1, workflowsEvaluated: 1, snapshotsWritten: 2 })-- const rows = await getSnapshots()- expect(rows).toHaveLength(2)- const workflowRow = rows.find((r) => r.hog_flow_id === flow.id)- expect(workflowRow).toMatchObject({ scope: 'workflow', state: 'critical', emails_sent: '1000' })- expect(workflowRow.bounce_rate).toBeCloseTo(0.06)- expect(rows.find((r) => r.hog_flow_id === null)).toMatchObject({ scope: 'team', state: 'critical' })-- // Same evaluatedAt (a Temporal activity retry) dedupes on the unique index- const retry = await service.evaluateTeamBatch([teamId], EVALUATED_AT)- expect(retry.snapshotsWritten).toEqual(0)- expect(await getSnapshots()).toHaveLength(2)-- // A later run appends new history rows instead of updating in place- await service.evaluateTeamBatch([teamId], '2026-07-11T06:00:00.000Z')- expect(await getSnapshots()).toHaveLength(4)- })-- it('computes rates over the most recent target volume, keeping an old batch until newer sends displace it', async () => {- const flow = await insertEmailFlow()- // A 5%-bounce batch 6 days ago and only 400 newer clean sends: the window (target 1000)- // still reaches back to the batch, so it keeps counting — no fixed-24h cliff.- mockMetrics([- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(144), sent: 1000, bounced: 50, complained: 0 },- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(2), sent: 400, bounced: 0, complained: 0 },- ])- await service.evaluateTeamBatch([teamId], EVALUATED_AT)-- let workflowRow = (await getSnapshots()).find((r) => r.hog_flow_id === flow.id)- // 1400 sent / 50 bounced ≈ 3.6% → warning (diluted below the 5% critical line but still counted)- expect(workflowRow).toMatchObject({ state: 'warning', emails_sent: '1400' })- expect(workflowRow.bounce_rate).toBeCloseTo(50 / 1400)-- // Once newer volume alone reaches the target, the old batch falls out of the window- mockMetrics([- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(144), sent: 1000, bounced: 50, complained: 0 },- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(2), sent: 1000, bounced: 5, complained: 0 },- ])- await service.evaluateTeamBatch([teamId], '2026-07-11T06:00:00.000Z')-- const laterRows = await getSnapshots()- workflowRow = laterRows.filter((r) => r.hog_flow_id === flow.id).at(-1)- expect(workflowRow).toMatchObject({ state: 'healthy', emails_sent: '1000' })- expect(workflowRow.bounce_rate).toBeCloseTo(0.005)- })-- it('judges a high-volume sender on at least the minimum window, not just the newest buckets', async () => {- const flow = await insertEmailFlow()- // The newest bucket alone exceeds the 1000-send target and is clean; the bad blast 20h- // earlier is inside the 24h floor and must still count — stopping at the volume target- // would report this sender healthy while the shared account absorbed 10% bounces.- mockMetrics([- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(2), sent: 5000, bounced: 0, complained: 0 },- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(20), sent: 5000, bounced: 500, complained: 0 },- ])-- await service.evaluateTeamBatch([teamId], EVALUATED_AT)-- const workflowRow = (await getSnapshots()).find((r) => r.hog_flow_id === flow.id)- // 10000 sent / 500 bounced = 5% → critical- expect(workflowRow).toMatchObject({ state: 'critical', emails_sent: '10000' })- expect(workflowRow.bounce_rate).toBeCloseTo(0.05)- })-- it('counts late-arriving bounces from bounce-only buckets newer than the sends', async () => {- const flow = await insertEmailFlow()- mockMetrics([- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(10), sent: 1000, bounced: 10, complained: 0 },- // Bounces that arrived hours after the send, in a bucket with zero sends- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(3), sent: 0, bounced: 45, complained: 0 },- ])-- await service.evaluateTeamBatch([teamId], EVALUATED_AT)-- const workflowRow = (await getSnapshots()).find((r) => r.hog_flow_id === flow.id)- // 55/1000 = 5.5% → critical; dropping the bounce-only bucket would misreport 1% healthy- expect(workflowRow).toMatchObject({ state: 'critical' })- expect(workflowRow.bounce_rate).toBeCloseTo(0.055)- })-- it('folds batch-job metrics into the parent workflow and counts orphans only at team level', async () => {- const flow = await insertEmailFlow()- const batchJobId = await insertBatchJob(flow.id)- mockMetrics([- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(4), sent: 400, bounced: 4, complained: 0 },- { teamId, appSourceId: batchJobId, hourBucket: HOURS_AGO(3), sent: 600, bounced: 20, complained: 0 },- // Matches neither a flow nor a batch job (e.g. deleted flow): team aggregate only- { teamId, appSourceId: randomUUID(), hourBucket: HOURS_AGO(2), sent: 100, bounced: 100, complained: 0 },- // Cross-team app_source_id (another team's metrics naming our flow): must not touch- // our workflow snapshot, and counts only toward the foreign team's aggregate- {- teamId: teamId + 1,- appSourceId: flow.id,- hourBucket: HOURS_AGO(2),- sent: 500,- bounced: 250,- complained: 0,- },- ])-- await service.evaluateTeamBatch([teamId], EVALUATED_AT)-- const rows = await getSnapshots()- const workflowRow = rows.find((r) => r.hog_flow_id === flow.id)- // 400+600 sent, 4+20 bounced = 2.4% → warning- expect(workflowRow).toMatchObject({ state: 'warning', emails_sent: '1000' })- expect(workflowRow.bounce_rate).toBeCloseTo(0.024)-- const teamRow = rows.find((r) => r.hog_flow_id === null)- // Orphan row included: 1100 sent, 124 bounced ≈ 11.3% → critical- expect(teamRow).toMatchObject({ state: 'critical', emails_sent: '1100' })- })-- it('pools the tenant rate across workflows instead of averaging or escalating per-workflow states', async () => {- const bigFlow = await insertEmailFlow()- const toxicFlow = await insertEmailFlow()- mockMetrics([- { teamId, appSourceId: bigFlow.id, hourBucket: HOURS_AGO(4), sent: 50000, bounced: 150, complained: 0 },- { teamId, appSourceId: toxicFlow.id, hourBucket: HOURS_AGO(3), sent: 2000, bounced: 160, complained: 0 },- ])-- await service.evaluateTeamBatch([teamId], EVALUATED_AT)-- const rows = await getSnapshots()- // Per workflow: each judged on its own stream- expect(rows.find((r) => r.hog_flow_id === bigFlow.id)).toMatchObject({ state: 'healthy' })- expect(rows.find((r) => r.hog_flow_id === toxicFlow.id)).toMatchObject({ state: 'critical' })-- // Tenant: pooled bounces / pooled sends (what SES's account ledger sees) ≈ 0.6% → healthy.- // Escalating to the worst workflow state would say critical; averaging the two rates- // (~4.2%) would say warning — both are wrong.- const teamRow = rows.find((r) => r.hog_flow_id === null)- expect(teamRow).toMatchObject({ state: 'healthy', emails_sent: '52000' })- expect(teamRow.bounce_rate).toBeCloseTo(310 / 52000)- })-- it('writes a carry-forward team snapshot when a recently evaluated team goes silent', async () => {- const flow = await insertEmailFlow()- mockMetrics([- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(2), sent: 1000, bounced: 60, complained: 0 },- ])- await service.evaluateTeamBatch([teamId], EVALUATED_AT)-- // Next run: no sends at all — the team still enters the plan via its recent snapshot...- mockMetrics([])- const nextRun = '2026-07-11T06:00:00.000Z'- const plan = await service.fetchTeamsToEvaluate(nextRun, 0, 5000)- expect(plan.teamIds).toContain(teamId)-- // ...and gets an explicit zero-volume row instead of yesterday's critical staying "current"- await service.evaluateTeamBatch([teamId], nextRun)- const teamRows = (await getSnapshots()).filter((r) => r.hog_flow_id === null)- expect(teamRows.at(-1)).toMatchObject({ state: 'insufficient_data', emails_sent: '0' })- })-- describe('representative volume sizing (multiplier 3, the default)', () => {- const buckets = (rows: [hoursAgo: number, sent: number][]): Map<number, ReputationMetrics> =>- new Map(rows.map(([hoursAgo, sent]) => [HOURS_AGO(hoursAgo), { sent, bounced: 0, complained: 0 }]))-- it.each([- ['floor wins for tiny senders', buckets([[2, 200]]), 1000],- ['multiplier times the biggest day wins for bigger senders', buckets([[2, 5000]]), 15000],- [- // Anchoring on the biggest single day (not an average) is what keeps a bursty- // sender's window spanning multiple campaigns: this sender's daily average is- // well under one batch, and average-based sizing would collapse the window.- 'bursty sender sizes from the biggest day, not the average',- buckets([- [2, 10000],- [26, 100],- [50, 100],- ]),- 30000,- ],- ['no sends at all falls back to the floor', new Map(), 1000],- [- 'a day of only late-arriving bounces contributes zero volume',- new Map([[HOURS_AGO(2), { sent: 0, bounced: 50, complained: 0 }]]),- 1000,- ],- ])('%s', (_name, input: Map<number, ReputationMetrics>, expected: number) => {- expect(representativeVolume(input, 1000, 3)).toEqual(expected)- })-- let scaledService: EmailReputationService- beforeEach(() => {- 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 () => {- const flow = await insertEmailFlow()- // Yesterday: 1000-send batch at 50% hard bounce. Today: a clean 1000-send batch.- // With a fixed 1000-send window today's batch alone would fill it and report 0%- // healthy — a false all-clear on the exact signal enforcement decisions use. The- // representative volume (3 × the 1000-send max day = 3000) keeps reaching back.- mockMetrics([- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(26), sent: 1000, bounced: 500, complained: 0 },- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(2), sent: 1000, bounced: 0, complained: 0 },- ])-- await scaledService.evaluateTeamBatch([teamId], EVALUATED_AT)-- const teamRow = (await getSnapshots()).find((r) => r.hog_flow_id === null)- // 500 bounced / 2000 sent = 25% — still critical, decaying by dilution not amnesia- expect(teamRow).toMatchObject({ state: 'critical', emails_sent: '2000' })- expect(teamRow.bounce_rate).toBeCloseTo(0.25)- })-- it('a weekly batch sender`s window spans its last batches across silent days', async () => {- const flow = await insertEmailFlow()- // 10k batch last Monday at 6% bounce, clean 10k batch today, nothing in between.- // The representative volume is 3 × 10k: sized from the biggest day, the window- // reaches across the silent week to the previous batch instead of judging this- // sender on today's single clean campaign.- mockMetrics([- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(170), sent: 10000, bounced: 600, complained: 0 },- { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(2), sent: 10000, bounced: 0, complained: 0 },- ])-- await scaledService.evaluateTeamBatch([teamId], EVALUATED_AT)-- const teamRow = (await getSnapshots()).find((r) => r.hog_flow_id === null)- // 600 / 20000 = 3% — warning: last week's bad batch still counts, diluted by the clean one- expect(teamRow).toMatchObject({ state: 'warning', emails_sent: '20000' })- 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.tsdeleted file mode 100644index b20ccafb8b77..000000000000--- a/nodejs/src/cdp/services/email-reputation/email-reputation.service.ts+++ /dev/null@@ -1,534 +0,0 @@-import { ClickHouseClient } from '@clickhouse/client'-import { randomUUID } from 'crypto'-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}$/i--const reputationSnapshotsCounter = new Counter({- name: 'email_reputation_snapshots_total',- help: 'Email reputation snapshot rows written by the evaluator',- labelNames: ['scope', 'state'],-})--interface HogFlowRow {- id: string- team_id: number-}--export interface EmailReputationServiceConfig {- /** Floor for each target's representative volume — small senders' windows stretch back- * (up to the lookback) until at least this many sends are covered. */- targetVolume: number- /** ...and must span at least this many hours — so a high-volume sender is judged on at- * least a full day of mail, not just the newest buckets that happen to reach the volume. */- minWindowHours: number- /** How far back to scan for that volume. Bounded by app_metrics2's 90-day TTL. */- lookbackDays: number- /** Scales each target's representative volume to its own sending scale:- * volume = max(targetVolume, multiplier × its biggest sending day in the lookback).- * This is what makes the window span multiple campaigns — see representativeVolume(). */- representativeVolumeMultiplier: number- thresholds: ReputationThresholds-}--interface SnapshotRow {- teamId: number- hogFlowId: string | null- scope: 'workflow' | 'team'- state: string- bounceRate: number- complaintRate: number- emailsSent: number-}--/**- * Computes per-workflow and per-team email sender reputation snapshots from app_metrics2.- * Calculation only — no enforcement. Each daily run appends one snapshot row per target to- * posthog_emailreputationsnapshot, so the table doubles as a time series for trend dashboards.- *- * Rates are volume-based, mirroring how AWS SES judges the shared sending account: each target's- * bounce/complaint rate covers at least its most recent representative volume of sends AND at- * least the last `minWindowHours` — whichever reaches further back (walking hourly buckets- * backwards from the evaluation time, capped at `lookbackDays`). The representative volume is- * sized to the target's own scale — `max(targetVolume, multiplier × its biggest sending day)` —- * so the window always spans multiple typical campaigns: a weekly batch blast keeps counting- * until enough newer batches dilute it (one clean batch can't wash it out), and a high-volume- * sender can't bury a bad morning under a few clean recent hours. Because each window ends at- * evaluation time, bounces that arrive hours after their send are picked up by the next run- * automatically.- *- * Runs as Temporal activities: the workflow fetches the team list once, then evaluates teams in- * paced batches. All rows of a run share the workflow's `evaluatedAt`, and inserts are- * ON CONFLICT DO NOTHING against a unique (team, hog_flow, evaluated_at) index, so activity- * retries are idempotent.- */-export class EmailReputationService {- constructor(- private clickhouse: ClickHouseClient,- private postgres: PostgresRouter,- private teamManager: TeamManager,- private config: EmailReputationServiceConfig- ) {}-- /**- * One page of teams to evaluate: those that sent workflow email within the lookback, plus- * teams with a recent nonzero snapshot that have gone silent — the latter get an explicit- * carry-forward snapshot so "latest reputation" never silently goes stale.- *- * Cursor-paginated by team id (activity results ride Temporal workflow history, so the full- * fleet-wide id list must never be one payload): both sources are queried for ids >- * `cursorTeamId` in id order, merged, and truncated to `pageSize`; `nextCursor` is null on- * the last page.- */- public async fetchTeamsToEvaluate(- evaluatedAt: string,- cursorTeamId: number,- pageSize: number- ): Promise<{ teamIds: number[]; nextCursor: number | null }> {- const result = await this.clickhouse.query({- query: `- SELECT DISTINCT team_id- FROM app_metrics2- WHERE app_source = 'hog_flow'- AND metric_kind = 'email'- AND metric_name = 'email_sent'- AND team_id > {cursorTeamId:UInt64}- AND timestamp >= parseDateTimeBestEffort({evaluatedAt:String}) - INTERVAL {lookbackDays:UInt32} DAY- AND timestamp < parseDateTimeBestEffort({evaluatedAt:String})- ORDER BY team_id- LIMIT {pageSize:UInt32}- `,- query_params: { evaluatedAt, cursorTeamId, pageSize, lookbackDays: this.config.lookbackDays },- format: 'JSONEachRow',- })- const rows = await result.json<{ team_id: number | string }>()- const teamIds = new Set(rows.map((row) => Number(row.team_id)))-- const recentlyEvaluated = await this.postgres.query<{ team_id: number }>(- PostgresUse.COMMON_READ,- `SELECT DISTINCT team_id FROM posthog_emailreputationsnapshot- WHERE hog_flow_id IS NULL AND emails_sent > 0 AND team_id > $3- AND evaluated_at >= $1::timestamptz - make_interval(days => $2)- ORDER BY team_id LIMIT $4`,- [evaluatedAt, this.config.lookbackDays, cursorTeamId, pageSize],- 'emailReputationFetchRecentTeams'- )- for (const row of recentlyEvaluated.rows) {- teamIds.add(Number(row.team_id))- }-- // Both sources returned their first `pageSize` ids after the cursor, so the merged set's- // first `pageSize` ids are complete — anything beyond belongs to a later page.- const merged = [...teamIds].sort((a, b) => a - b)- const page = merged.slice(0, pageSize)- const hasMore =- merged.length > pageSize || rows.length === pageSize || recentlyEvaluated.rows.length === pageSize- return { teamIds: page, nextCursor: hasMore && page.length > 0 ? page[page.length - 1] : null }- }-- /**- * Evaluate one batch of teams: fetch their hourly metrics, attribute them to workflows,- * accumulate each target's most recent sends up to the target volume, classify, and append- * snapshot rows. Anchored on `evaluatedAt` so a retried batch reads the same buckets and- * dedupes against rows it already wrote.- */- public async evaluateTeamBatch(teamIds: number[], evaluatedAt: string): Promise<BatchEvaluationSummary> {- const summary: BatchEvaluationSummary = {- teamsEvaluated: 0,- workflowsEvaluated: 0,- snapshotsWritten: 0,- }- if (teamIds.length === 0) {- return summary- }-- const rows = await this.fetchHourlyEmailMetrics(teamIds, evaluatedAt)- const { flows, sourceToFlow } = await this.resolveSources([...new Set(rows.map((r) => r.appSourceId))])- const snapshots: SnapshotRow[] = []- const minWindowStart = Math.floor(Date.parse(evaluatedAt) / 1000) - this.config.minWindowHours * 3600-- // Per-workflow: fold each source's hourly buckets into its workflow, then take each- // workflow's window (>= minWindowHours and >= its representative volume of sends).- const workflowBuckets = new Map<string, Map<number, ReputationMetrics>>()- for (const row of rows) {- const flowId = sourceToFlow.get(row.appSourceId)- if (!flowId) {- continue- }- // Defense in depth: the flow lookups aren't team-filtered, so a cross-team- // app_source_id would otherwise attribute one team's bounces to another team's- // workflow snapshot. Mismatched rows still count toward their own team's aggregate.- const flow = flows.get(flowId)- if (!flow || flow.team_id !== row.teamId) {- continue- }- addBucket(getOrCreate(workflowBuckets, flowId), row)- }- for (const [flowId, buckets] of workflowBuckets) {- const flow = flows.get(flowId)- if (!flow) {- continue- }- const totals = accumulateRecentVolume(buckets, this.representativeVolume(buckets), minWindowStart)- const { state, bounceRate, complaintRate } = classifyReputation(totals, this.config.thresholds)- snapshots.push({- teamId: flow.team_id,- hogFlowId: flow.id,- scope: 'workflow',- state,- bounceRate,- complaintRate,- emailsSent: totals.sent,- })- summary.workflowsEvaluated++- }-- // Per-team: the aggregate takes its own most-recent-volume window over ALL the team's- // email (including sources that no longer resolve to a workflow), independent of the- // per-workflow windows — mirroring the account-level rate SES computes.- const teamBuckets = new Map<number, Map<number, ReputationMetrics>>()- for (const row of rows) {- addBucket(getOrCreate(teamBuckets, row.teamId), row)- }- for (const teamId of teamIds) {- const buckets = teamBuckets.get(teamId)- // No activity in the lookback: carry-forward snapshot. The team only entered the plan- // via a recent nonzero snapshot, so record an explicit "no recent volume" row rather- // than leaving a stale rate presented as current.- const totals = buckets- ? accumulateRecentVolume(buckets, this.representativeVolume(buckets), minWindowStart)- : { sent: 0, bounced: 0, complained: 0 }- const { state, bounceRate, complaintRate } = classifyReputation(totals, this.config.thresholds)- snapshots.push({- teamId,- hogFlowId: null,- scope: 'team',- state,- bounceRate,- complaintRate,- emailsSent: totals.sent,- })- 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)- }- }- }-- logger.info('[EmailReputation] evaluated batch', {- teams: summary.teamsEvaluated,- workflows: summary.workflowsEvaluated,- snapshotsWritten: summary.snapshotsWritten,- evaluatedAt,- })- return summary- }-- private async fetchHourlyEmailMetrics(teamIds: number[], evaluatedAt: string): Promise<HourlyEmailMetricsRow[]> {- const result = await this.clickhouse.query({- // email_blocked is how SES complaint events are recorded (see helpers/ses.ts), hence- // the `complained` alias. email_bounced_hard counts only Permanent bounces, matching- // AWS's account bounce rate (which excludes transient greylisting/mailbox-full- // traffic). The metric is emitted from the same deploy that created the snapshot- // table, so windows reaching back before that deploy undercount bounces until it has- // volume-window depth — acceptable while the score is visibility-only. No HAVING sent > 0: buckets holding only late-arriving- // bounces/complaints must still count toward the window they fall into.- query: `- SELECT- team_id,- app_source_id,- toUnixTimestamp(toStartOfHour(timestamp)) AS hour_bucket,- sumIf(count, metric_name = 'email_sent') AS sent,- sumIf(count, metric_name = 'email_bounced_hard') AS bounced,- sumIf(count, metric_name = 'email_blocked') AS complained- FROM app_metrics2- WHERE app_source = 'hog_flow'- AND metric_kind = 'email'- AND metric_name IN ('email_sent', 'email_bounced_hard', 'email_blocked')- AND team_id IN ({teamIds:Array(UInt64)})- AND timestamp >= parseDateTimeBestEffort({evaluatedAt:String}) - INTERVAL {lookbackDays:UInt32} DAY- AND timestamp < parseDateTimeBestEffort({evaluatedAt:String})- GROUP BY team_id, app_source_id, hour_bucket- `,- query_params: { teamIds, evaluatedAt, lookbackDays: this.config.lookbackDays },- format: 'JSONEachRow',- })- const rows = await result.json<{- team_id: number | string- app_source_id: string- hour_bucket: number | string- sent: number | string- bounced: number | string- complained: number | string- }>()-- return rows.map((row) => ({- teamId: Number(row.team_id),- appSourceId: row.app_source_id,- hourBucket: Number(row.hour_bucket),- sent: Number(row.sent),- bounced: Number(row.bounced),- complained: Number(row.complained),- }))- }-- /**- * Resolve app_source_ids to workflows. Batch-triggered runs record metrics under the batch-job- * id (`parentRunId`), not the workflow id — and batch broadcasts are the highest-risk email- * blasts — so unmatched ids are resolved through workflows_hogflowbatchjob and folded into the- * parent workflow. Ids matching neither (deleted flows, plain hog functions) resolve to- * nothing and only count toward the team aggregate.- */- private async resolveSources(rawSourceIds: string[]): Promise<{- flows: Map<string, HogFlowRow>- sourceToFlow: Map<string, string>- }> {- // app_source_id comes straight from ClickHouse; a single non-UUID value would abort the- // whole batch on the uuid[] casts below and poison the run until the row ages out.- // Non-UUID sources can't be a workflow or batch job anyway — they only count team-level.- const sourceIds = rawSourceIds.filter((id) => UUID_REGEX.test(id))- const flows = await this.fetchHogFlows(sourceIds)- const sourceToFlow = new Map<string, string>()- for (const id of sourceIds) {- if (flows.has(id)) {- sourceToFlow.set(id, id)- }- }-- const unmatched = sourceIds.filter((id) => !sourceToFlow.has(id))- const batchJobToFlow = await this.fetchBatchJobFlowIds(unmatched)- const extraFlowIds = [...new Set(batchJobToFlow.values())].filter((id) => !flows.has(id))- for (const [id, flow] of await this.fetchHogFlows(extraFlowIds)) {- flows.set(id, flow)- }- for (const [batchJobId, flowId] of batchJobToFlow) {- if (flows.has(flowId)) {- sourceToFlow.set(batchJobId, flowId)- }- }-- return { flows, sourceToFlow }- }-- private async fetchBatchJobFlowIds(ids: string[]): Promise<Map<string, string>> {- if (ids.length === 0) {- return new Map()- }- const result = await this.postgres.query<{ id: string; hog_flow_id: string }>(- PostgresUse.COMMON_READ,- `SELECT id, hog_flow_id FROM workflows_hogflowbatchjob WHERE id = ANY($1)`,- [ids],- 'emailReputationFetchBatchJobs'- )- return new Map(result.rows.map((row) => [row.id, row.hog_flow_id]))- }-- private async fetchHogFlows(ids: string[]): Promise<Map<string, HogFlowRow>> {- if (ids.length === 0) {- return new Map()- }- const result = await this.postgres.query<HogFlowRow>(- PostgresUse.COMMON_READ,- `SELECT id, team_id FROM posthog_hogflow WHERE id = ANY($1)`,- [ids],- 'emailReputationFetchHogFlows'- )- return new Map(result.rows.map((row) => [row.id, row]))- }-- private representativeVolume(buckets: Map<number, ReputationMetrics>): number {- 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(- PostgresUse.COMMON_WRITE,- `INSERT INTO posthog_emailreputationsnapshot- (id, team_id, hog_flow_id, scope, state, bounce_rate, complaint_rate, emails_sent,- evaluated_at, created_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())- ON CONFLICT DO NOTHING`,- [- randomUUID(),- snapshot.teamId,- snapshot.hogFlowId,- snapshot.scope,- snapshot.state,- snapshot.bounceRate,- snapshot.complaintRate,- snapshot.emailsSent,- evaluatedAt,- ],- 'emailReputationInsertSnapshot'- )- return (result.rowCount ?? 0) > 0- }-}--function getOrCreate<K>(map: Map<K, Map<number, ReputationMetrics>>, key: K): Map<number, ReputationMetrics> {- let value = map.get(key)- if (!value) {- value = new Map()- map.set(key, value)- }- return value-}--function addBucket(buckets: Map<number, ReputationMetrics>, row: HourlyEmailMetricsRow): void {- const acc = buckets.get(row.hourBucket) ?? { sent: 0, bounced: 0, complained: 0 }- acc.sent += row.sent- acc.bounced += row.bounced- acc.complained += row.complained- buckets.set(row.hourBucket, acc)-}--/**- * Sizes a target's representative volume from its own sending scale, mirroring AWS SES's stated- * principle that rates are computed over "representative volume" sized to limit the influence of- * any single campaign:- *- * volume = max(floor, multiplier × biggest sending day in the buckets)- *- * Anchoring on the biggest single day (rather than an average) is what makes bursty senders- * work: a weekly 10k batch sender averages ~1.4k/day — under one campaign — but their max day- * is 10k, so their window spans their last `multiplier` batches. The guarantee this buys: no- * single day can contribute more than 1/multiplier of the window, so one clean campaign can- * never fully wash out yesterday's disaster, and redemption means sending `multiplier` clean- * campaigns. Days are UTC calendar days, matching the daily evaluation cadence.- */-export function representativeVolume(- buckets: Map<number, ReputationMetrics>,- floor: number,- multiplier: number-): number {- const sentByDay = new Map<number, number>()- for (const [hour, bucket] of buckets) {- const day = Math.floor(hour / 86400)- sentByDay.set(day, (sentByDay.get(day) ?? 0) + bucket.sent)- }- const maxDaily = Math.max(0, ...sentByDay.values())- return Math.max(floor, multiplier * maxDaily)-}--/**- * Walk hourly buckets (keyed by epoch seconds) newest-first. Every bucket at or after- * `minWindowStart` is included unconditionally — a high-volume sender is judged on at least that- * span, so a bad morning can't hide behind a few clean recent hours. Older buckets are then- * included until the target send volume is reached (the crossing bucket counts whole — hourly- * granularity), which is what stretches the window for low-volume senders. Bounce-only buckets- * are naturally included, which is how late-arriving bounces get counted.- */-export function accumulateRecentVolume(- buckets: Map<number, ReputationMetrics>,- targetVolume: number,- minWindowStart: number-): ReputationMetrics {- const hours = [...buckets.keys()].sort((a, b) => b - a)- const totals: ReputationMetrics = { sent: 0, bounced: 0, complained: 0 }- for (const hour of hours) {- if (hour < minWindowStart && totals.sent >= targetVolume) {- break- }- const bucket = buckets.get(hour)!- totals.sent += bucket.sent- totals.bounced += bucket.bounced- totals.complained += bucket.complained- }- return totals-}diff --git a/nodejs/src/cdp/services/email-reputation/temporal/activities.ts b/nodejs/src/cdp/services/email-reputation/temporal/activities.tsdeleted file mode 100644index cbf51b339fbf..000000000000--- a/nodejs/src/cdp/services/email-reputation/temporal/activities.ts+++ /dev/null@@ -1,40 +0,0 @@-import { EmailReputationService } from '../email-reputation.service'-import { BatchEvaluationSummary } from '../types'--// One plan page ≈ pageSize ids (bounded well under Temporal's payload limits); the workflow-// walks pages via nextCursor so the fleet-wide team list never rides one activity result.-export const EVALUATION_PLAN_PAGE_SIZE = 5000--export interface EvaluationPlanPage {- teamIds: number[]- nextCursor: number | null- batchSize: number- batchDelayMs: number-}--export interface EmailReputationActivities {- fetchTeamsToEvaluate: (evaluatedAt: string, cursorTeamId: number) => Promise<EvaluationPlanPage>- evaluateTeamBatch: (teamIds: number[], evaluatedAt: string) => Promise<BatchEvaluationSummary>-}--/**- * Activity payloads ride Temporal workflow history (~2 MiB cap per payload). Only bounded pages- * of team ids and counts cross the boundary — metric rows and snapshots stay inside the batch- * activity.- */-export function createActivities(- service: EmailReputationService,- pacing: { batchSize: number; batchDelayMs: number }-): EmailReputationActivities {- return {- fetchTeamsToEvaluate: async (evaluatedAt, cursorTeamId) => {- const { teamIds, nextCursor } = await service.fetchTeamsToEvaluate(- evaluatedAt,- cursorTeamId,- EVALUATION_PLAN_PAGE_SIZE- )- return { teamIds, nextCursor, batchSize: pacing.batchSize, batchDelayMs: pacing.batchDelayMs }- },- evaluateTeamBatch: (teamIds, evaluatedAt) => service.evaluateTeamBatch(teamIds, evaluatedAt),- }-}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.tsdeleted file mode 100644index ee8e106bb7e6..000000000000--- a/nodejs/src/cdp/services/email-reputation/temporal/email-reputation-worker.service.ts+++ /dev/null@@ -1,221 +0,0 @@-import { createClient as createClickHouseClient } from '@clickhouse/client'-import { Client, Connection, ScheduleAlreadyRunning, ScheduleOverlapPolicy } from '@temporalio/client'-import { DataConverter } from '@temporalio/common'-import { NativeConnection, Worker } from '@temporalio/worker'-import * as fs from 'fs/promises'-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,- HealthCheckResultOk,- PluginServerService,- PluginsServerConfig,-} from '~/types'--import { EmailReputationService } from '../email-reputation.service'-import { createActivities } from './activities'--export const EMAIL_REPUTATION_TASK_QUEUE = 'email-reputation-task-queue'-export const EMAIL_REPUTATION_SCHEDULE_ID = 'email-reputation-evaluation'-export const EMAIL_REPUTATION_WORKFLOW_TYPE = 'emailReputationEvaluation'--/**- * Hosts the Temporal worker for the daily email reputation snapshot run inside the plugin server- * and idempotently ensures the Temporal Schedule that triggers it. Follows the session-replay- * rasterizer's Temporal setup (TLS + payload encryption) but registers a TS workflow via- * workflowsPath rather than activities only.- */-export class EmailReputationWorkerService {- private worker?: Worker- private workerConnection?: NativeConnection- private clientConnection?: Connection- private runPromise?: Promise<void>- private runError?: Error-- constructor(- private config: PluginsServerConfig,- private deps: { postgres: PostgresRouter }- ) {}-- public async start(): Promise<void> {- const service = this.buildReputationService()- const address = `${this.config.TEMPORAL_HOST}:${this.config.TEMPORAL_PORT || '7233'}`- const namespace = this.config.TEMPORAL_NAMESPACE || 'default'- const tls = await this.buildTLSConfig()- const dataConverter = this.buildDataConverter()-- this.workerConnection = await NativeConnection.connect({ address, tls: tls ?? undefined })- this.worker = await Worker.create({- connection: this.workerConnection,- namespace,- taskQueue: EMAIL_REPUTATION_TASK_QUEUE,- workflowsPath: require.resolve('./workflow'),- activities: createActivities(service, {- batchSize: this.config.EMAIL_REPUTATION_BATCH_SIZE,- batchDelayMs: this.config.EMAIL_REPUTATION_BATCH_DELAY_SECONDS * 1000,- }),- maxConcurrentActivityTaskExecutions: 2,- dataConverter,- })-- // Handled, not rethrown: an unobserved rejection here would trip the process-level- // unhandledRejection handler and stop the whole plugin server (in dev this capability- // rides along with the full CDP set). isHealthy() surfaces the crash instead.- this.runPromise = this.worker.run().catch((error) => {- this.runError = error instanceof Error ? error : new Error(String(error))- logger.error('[EmailReputationWorker] worker crashed', { error })- })-- this.clientConnection = await Connection.connect({ address, tls: tls ?? false })- const client = new Client({ connection: this.clientConnection, namespace, dataConverter })- await this.ensureSchedule(client)-- logger.info('[EmailReputationWorker] started', { address, taskQueue: EMAIL_REPUTATION_TASK_QUEUE })- }-- private buildReputationService(): EmailReputationService {- // Internal ClickHouse uses self-signed certs with a hostname mismatch, same as the- // cdp-rerun-worker and session-replay recording-api clients.- const chScheme = this.config.CLICKHOUSE_SECURE ? 'https' : 'http'- const chPort = this.config.CLICKHOUSE_SECURE ? 8443 : 8123- const clickhouse = createClickHouseClient({- url: `${chScheme}://${this.config.CLICKHOUSE_HOST}:${chPort}`,- username: this.config.CLICKHOUSE_USER,- password: this.config.CLICKHOUSE_PASSWORD || undefined,- database: this.config.CLICKHOUSE_DATABASE,- request_timeout: 60_000,- max_open_connections: 10,- ...(this.config.CLICKHOUSE_SECURE- ? {- http_agent: new https.Agent({ rejectUnauthorized: false, keepAlive: true, maxSockets: 10 }), // nosemgrep: problem-based-packs.insecure-transport.js-node.bypass-tls-verification.bypass-tls-verification- }- : {}),- })- 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,- representativeVolumeMultiplier: this.config.EMAIL_REPUTATION_VOLUME_MULTIPLIER,- thresholds: {- minSends: this.config.EMAIL_REPUTATION_MIN_SENDS,- bounceWarning: this.config.EMAIL_REPUTATION_BOUNCE_WARNING_RATE,- bounceCritical: this.config.EMAIL_REPUTATION_BOUNCE_CRITICAL_RATE,- complaintWarning: this.config.EMAIL_REPUTATION_COMPLAINT_WARNING_RATE,- complaintCritical: this.config.EMAIL_REPUTATION_COMPLAINT_CRITICAL_RATE,- },- })- }-- private async ensureSchedule(client: Client): Promise<void> {- const hour = this.config.EMAIL_REPUTATION_EVALUATION_HOUR_UTC- try {- await client.schedule.create({- scheduleId: EMAIL_REPUTATION_SCHEDULE_ID,- spec: { calendars: [{ hour }] },- action: {- type: 'startWorkflow',- workflowType: EMAIL_REPUTATION_WORKFLOW_TYPE,- taskQueue: EMAIL_REPUTATION_TASK_QUEUE,- args: [],- },- policies: { overlap: ScheduleOverlapPolicy.SKIP },- })- logger.info('[EmailReputationWorker] created schedule', { hour })- } catch (error) {- if (error instanceof ScheduleAlreadyRunning) {- // Update the existing schedule so config stays authoritative (hour changes, or a- // stale spec left by an earlier build, would otherwise be silently ignored forever).- await client.schedule.getHandle(EMAIL_REPUTATION_SCHEDULE_ID).update((previous) => ({- ...previous,- spec: { calendars: [{ hour }] },- // Reassert the action too: a schedule left by an older build could otherwise- // keep dispatching a stale workflow type/queue/args forever.- action: {- type: 'startWorkflow',- workflowType: EMAIL_REPUTATION_WORKFLOW_TYPE,- taskQueue: EMAIL_REPUTATION_TASK_QUEUE,- args: [],- },- policies: { ...previous.policies, overlap: ScheduleOverlapPolicy.SKIP },- }))- logger.info('[EmailReputationWorker] updated existing schedule', { hour })- return- }- throw error- }- }-- private async buildTLSConfig(): Promise<{- serverRootCACertificate: Buffer- clientCertPair: { crt: Buffer; key: Buffer }- } | null> {- const { TEMPORAL_CLIENT_ROOT_CA, TEMPORAL_CLIENT_CERT, TEMPORAL_CLIENT_KEY } = this.config- if (!(TEMPORAL_CLIENT_ROOT_CA && TEMPORAL_CLIENT_CERT && TEMPORAL_CLIENT_KEY)) {- return null- }-- let systemCAs = Buffer.alloc(0)- try {- systemCAs = Buffer.from(await fs.readFile('/etc/ssl/certs/ca-certificates.crt'))- } catch {- // System CA bundle not found — use only the provided root CA- }-- return {- serverRootCACertificate: Buffer.concat([systemCAs, Buffer.from(TEMPORAL_CLIENT_ROOT_CA)]),- clientCertPair: {- crt: Buffer.from(TEMPORAL_CLIENT_CERT),- key: Buffer.from(TEMPORAL_CLIENT_KEY),- },- }- }-- private buildDataConverter(): DataConverter | undefined {- const { TEMPORAL_SECRET_KEY, TEMPORAL_FALLBACK_SECRET_KEYS } = this.config- if (!TEMPORAL_SECRET_KEY) {- logger.warn('[EmailReputationWorker] no TEMPORAL_SECRET_KEY configured — payloads will not be encrypted')- return undefined- }- const fallbackKeys = (TEMPORAL_FALLBACK_SECRET_KEYS ?? '')- .split(',')- .map((key) => key.trim())- .filter(Boolean)- return { payloadCodecs: [new EncryptionCodec(TEMPORAL_SECRET_KEY, fallbackKeys)] }- }-- public isHealthy(): HealthCheckResult {- const state = this.worker?.getState()- if (state !== 'RUNNING') {- return new HealthCheckResultError(- `Email reputation Temporal worker is ${state ?? 'not started'}${this.runError ? `: ${this.runError.message}` : ''}`,- {}- )- }- return new HealthCheckResultOk()- }-- public async stop(): Promise<void> {- // shutdown() throws IllegalStateError unless the worker is RUNNING (e.g. it already- // crashed) — skipping it must not skip the connection cleanup below.- if (this.worker?.getState() === 'RUNNING') {- this.worker.shutdown()- }- // run() resolves once shutdown drains in-flight activities- await this.runPromise?.catch(() => {})- await this.clientConnection?.close().catch(() => {})- await this.workerConnection?.close().catch(() => {})- }-- public get service(): PluginServerService {- return {- id: 'email-reputation-evaluator',- onShutdown: () => this.stop(),- healthcheck: () => this.isHealthy(),- }- }-}diff --git a/nodejs/src/cdp/services/email-reputation/temporal/workflow.ts b/nodejs/src/cdp/services/email-reputation/temporal/workflow.tsdeleted file mode 100644index 66cc3241a65f..000000000000--- a/nodejs/src/cdp/services/email-reputation/temporal/workflow.ts+++ /dev/null@@ -1,77 +0,0 @@-/**- * Temporal workflow: one daily email-reputation snapshot run, started by a Temporal Schedule- * (overlap: SKIP). Teams are evaluated in paced batches with durable sleeps in between, so the- * sweep doesn't hit ClickHouse/Postgres in one burst and resumes mid-run after a worker restart.- *- * Runs in Temporal's deterministic workflow sandbox — keep this file free of runtime imports- * other than @temporalio/workflow; all IO happens in the activities.- */-import { log, proxyActivities, sleep } from '@temporalio/workflow'--import type { EmailReputationActivities } from './activities'--const { fetchTeamsToEvaluate, evaluateTeamBatch } = proxyActivities<EmailReputationActivities>({- startToCloseTimeout: '10 minutes',- retry: {- maximumAttempts: 3,- initialInterval: '10s',- },-})--export interface EmailReputationEvaluationResult {- evaluatedAt: string- teamsEvaluated: number- workflowsEvaluated: number- snapshotsWritten: number- failedBatches: number-}--export async function emailReputationEvaluation(): Promise<EmailReputationEvaluationResult> {- // Captured once before any awaits: every batch (and any retry) shares one run timestamp, which- // both anchors the metrics window and dedupes re-inserted snapshot rows. The sandbox makes- // `new Date()` deterministic on replay.- const evaluatedAt = new Date().toISOString()-- const result: EmailReputationEvaluationResult = {- evaluatedAt,- teamsEvaluated: 0,- workflowsEvaluated: 0,- snapshotsWritten: 0,- failedBatches: 0,- }-- // The plan is cursor-paged so no single activity result carries the fleet-wide team list.- let cursor = 0- let firstBatch = true- for (;;) {- const page = await fetchTeamsToEvaluate(evaluatedAt, cursor)- const batchSize = Math.max(1, page.batchSize)- for (let offset = 0; offset < page.teamIds.length; offset += batchSize) {- if (!firstBatch && page.batchDelayMs > 0) {- await sleep(page.batchDelayMs)- }- firstBatch = false- const teamIds = page.teamIds.slice(offset, offset + batchSize)- try {- const summary = await evaluateTeamBatch(teamIds, evaluatedAt)- result.teamsEvaluated += summary.teamsEvaluated- result.workflowsEvaluated += summary.workflowsEvaluated- result.snapshotsWritten += summary.snapshotsWritten- } catch (error) {- // One poison batch must not starve every later-sorted team of snapshots for the- // day — the activity already retried; record and move on.- result.failedBatches++- log.error('email reputation batch failed after retries, continuing with remaining batches', {- teamIds,- error: error instanceof Error ? error.message : String(error),- })- }- }- if (page.nextCursor === null) {- break- }- cursor = page.nextCursor- }-- return result-}diff --git a/nodejs/src/cdp/services/email-reputation/types.ts b/nodejs/src/cdp/services/email-reputation/types.tsdeleted file mode 100644index 8da50d506e4d..000000000000--- a/nodejs/src/cdp/services/email-reputation/types.ts+++ /dev/null@@ -1,19 +0,0 @@-/** One hourly bucket of email metrics from app_metrics2 (timestamps there are hour-truncated).- * `appSourceId` is usually a HogFlow id but can be a batch-job id; rows that don't match a- * HogFlow still count toward the team aggregate. */-export interface HourlyEmailMetricsRow {- teamId: number- appSourceId: string- /** Epoch seconds of the hour bucket (avoids timezone-ambiguous datetime strings). */- hourBucket: number- sent: number- bounced: number- complained: number-}--/** Counts returned by a batch evaluation — snapshot rows never ride Temporal workflow history. */-export interface BatchEvaluationSummary {- teamsEvaluated: number- workflowsEvaluated: number- snapshotsWritten: number-}diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex bedba16b9b98..24edc936b9e1 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -51,7 +51,6 @@ export enum PluginServerMode {ingestion_v2_combined = 'ingestion-v2-combined',ingestion_traces = 'ingestion-traces',cdp_hogflow_scheduler = 'cdp-hogflow-scheduler',- email_reputation_evaluator = 'email-reputation-evaluator',ingestion_api = 'ingestion-api',}diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex 34c930e9d7d3..6072465ea18a 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -14,7 +14,6 @@ import { QuotaLimiting } from '~/common/services/quota-limiting.service'import { ServerCommands } from '~/common/utils/commands'import { PostgresRouter } from '~/common/utils/db/postgres'import { createRedisPoolFromConfig } from '~/common/utils/db/redis'-import { isDevEnv } from '~/common/utils/env-utils'import { GeoIPService } from '~/common/utils/geoip'import { logger } from '~/common/utils/logger'import { PubSub } from '~/common/utils/pubsub'@@ -41,7 +40,6 @@ import { createCdpProducerRegistry } from './cdp/outputs/producer-registry'import { CdpProducerName } from './cdp/outputs/producers'import { createCdpOutputsRegistry } from './cdp/outputs/registry'import { CyclotronV2JanitorService, CyclotronV2Manager, CyclotronV2Worker } from './cdp/services/cyclotron-v2'-import { EmailReputationWorkerService } from './cdp/services/email-reputation/temporal/email-reputation-worker.service'import { HogFlowScheduleService } from './cdp/services/hogflow-schedule/hogflow-schedule.service'import { HOGFLOW_BATCH_RESOLVE_QUEUE } from './cdp/services/hogflows/batch-resolver.types'import { HogFlowBatchPersonQueryService } from './cdp/services/hogflows/hogflow-batch-person-query.service'@@ -55,7 +53,7 @@ import { createSesRateLimiterValkeyPool } from './cdp/services/rate-limiter/rateimport { RateLimiterService } from './cdp/services/rate-limiter/rate-limiter.service'import { EncryptedFields } from './cdp/utils/encryption-utils'import { CleanupResources, NodeServer, ServerLifecycle } from './servers/base-server'-import { HealthCheckResultOk, PluginServerService, PluginsServerConfig, RedisPool } from './types'+import { PluginServerService, PluginsServerConfig, RedisPool } from './types'/*** PluginServer handles CDP, logs, evaluation scheduler, and local-dev combined modes.@@ -397,34 +395,6 @@ export class PluginServer implements NodeServer {})}- if (capabilities.emailReputationEvaluator) {- serviceLoaders.push(async () => {- const worker = new EmailReputationWorkerService(this.config, { postgres: this.postgres! })- try {- await worker.start()- } catch (error) {- // In dev this capability rides along with the full CDP set — don't take the whole- // plugin server down (or fail its /_health) when the local Temporal isn't running.- // Dedicated deployments should crash and restart.- if (isDevEnv()) {- logger.warn('[EmailReputationWorker] failed to start, continuing without it (dev only)', {- error,- })- // start() may have failed partway (worker already polling): tear down- // whatever came up so the stub doesn't hide an unsupervised worker.- await worker.stop().catch(() => {})- return {- id: 'email-reputation-evaluator',- onShutdown: () => Promise.resolve(),- healthcheck: () => new HealthCheckResultOk(),- }- }- throw error- }- return worker.service- })- }-// ServerCommands is always createdserviceLoaders.push(() => {const serverCommands = new ServerCommands(this.pubsub!)diff --git a/nodejs/src/types.ts b/nodejs/src/types.tsindex 937e3e3ca6dd..42174a615273 100644--- a/nodejs/src/types.ts+++ b/nodejs/src/types.ts@@ -157,7 +157,6 @@ export interface PluginServerCapabilities {cdpRerunWorker?: booleancdpHogflowScheduler?: booleancdpHogflowSubscriptionMatcher?: boolean- emailReputationEvaluator?: booleanrecordingApi?: booleaningestionV2Testing?: boolean}