Skip to content

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

feat(cdp): daily temporal evaluator for workflow email reputation (#72545)

Meikel Ratz1d5e77ad12fa
diff --git a/nodejs/package.json b/nodejs/package.json
index 8ca91410b388..aff075fb5088 100644
--- a/nodejs/package.json
+++ b/nodejs/package.json
@@ -103,6 +103,7 @@
"@temporalio/common": "1.15.0",
"@temporalio/proto": "1.15.0",
"@temporalio/worker": "1.15.0",
+ "@temporalio/workflow": "1.15.0",
"@types/node": "catalog:",
"@types/tail": "^2.2.1",
"avsc": "^5.7.9",
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.ts
index 115e34f3aa75..7768a292306e 100644
--- a/nodejs/src/capabilities.ts
+++ b/nodejs/src/capabilities.ts
@@ -30,6 +30,7 @@ export const CAPABILITIES_CDP_WORKFLOWS: PluginServerCapabilities = {
cdpCyclotronV2Janitor: isDevEnv(),
cdpHogflowScheduler: isDevEnv(),
cdpHogflowSubscriptionMatcher: isDevEnv(),
+ emailReputationEvaluator: isDevEnv(),
}
/** Realtime Cohorts - precalculated filters and cohort membership */
@@ -199,6 +200,10 @@ 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.ts
index 03472c61dc30..105128818c8a 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -18,6 +18,7 @@ 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
@@ -182,6 +183,19 @@ export type CdpConfig = ClickhouseConfig & {
CYCLOTRON_NODE_RESCHEDULE_CHUNK_SIZE: number
CYCLOTRON_NODE_RESCHEDULE_MAX_CHUNKS_PER_CALL: number
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_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 {
@@ -339,5 +353,21 @@ 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 TARGET_VOLUME sends — 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_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.ts
new file mode 100644
index 000000000000..cdcb917aa73e
--- /dev/null
+++ b/nodejs/src/cdp/services/email-reputation/classifier.test.ts
@@ -0,0 +1,30 @@
+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.ts
new file mode 100644
index 000000000000..4df0e926e6e4
--- /dev/null
+++ b/nodejs/src/cdp/services/email-reputation/classifier.ts
@@ -0,0 +1,64 @@
+/**
+ * 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.ts
new file mode 100644
index 000000000000..5a285e68e175
--- /dev/null
+++ b/nodejs/src/cdp/services/email-reputation/email-reputation.service.test.ts
@@ -0,0 +1,265 @@
+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 { createTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'
+import { Hub } from '~/types'
+
+import { DEFAULT_THRESHOLDS } from './classifier'
+import { EmailReputationService } from './email-reputation.service'
+import { HourlyEmailMetricsRow } from './types'
+
+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() }
+ service = new EmailReputationService(mockClickhouse as any, hub.postgres, {
+ targetVolume: 1000,
+ minWindowHours: 24,
+ lookbackDays: 30,
+ 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' })
+ })
+})
diff --git a/nodejs/src/cdp/services/email-reputation/email-reputation.service.ts b/nodejs/src/cdp/services/email-reputation/email-reputation.service.ts
new file mode 100644
index 000000000000..77e8fcf0b992
--- /dev/null
+++ b/nodejs/src/cdp/services/email-reputation/email-reputation.service.ts
@@ -0,0 +1,409 @@
+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 { ReputationMetrics, ReputationThresholds, classifyReputation } from './classifier'
+import { BatchEvaluationSummary, HourlyEmailMetricsRow } from './types'
+
+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 {
+ /** Each target's window must contain at least this many sends (SES-style
+ * "representative volume") — small senders' windows stretch back until it's met. */
+ 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
+ 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 `targetVolume` sends AND at least the
+ * last `minWindowHours` — whichever reaches further back (walking hourly buckets backwards from
+ * the evaluation time, capped at `lookbackDays`). A weekly batch blast keeps counting until
+ * enough newer volume dilutes it, 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 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 >= targetVolume 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.config.targetVolume, 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.config.targetVolume, 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++
+ }
+
+ for (const snapshot of snapshots) {
+ const inserted = await this.insertSnapshot(snapshot, evaluatedAt)
+ if (inserted) {
+ summary.snapshotsWritten++
+ reputationSnapshotsCounter.labels(snapshot.scope, snapshot.state).inc()
+ }
+ }
+
+ 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]))
+ }
+
+ /** 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)
+}
+
+/**
+ * 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.ts
new file mode 100644
index 000000000000..cbf51b339fbf
--- /dev/null
+++ b/nodejs/src/cdp/services/email-reputation/temporal/activities.ts
@@ -0,0 +1,40 @@
+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.ts
new file mode 100644
index 000000000000..e1110e484aec
--- /dev/null
+++ b/nodejs/src/cdp/services/email-reputation/temporal/email-reputation-worker.service.ts
@@ -0,0 +1,219 @@
+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 {
+ 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, {
+ targetVolume: this.config.EMAIL_REPUTATION_TARGET_VOLUME,
+ minWindowHours: this.config.EMAIL_REPUTATION_MIN_WINDOW_HOURS,
+ lookbackDays: this.config.EMAIL_REPUTATION_LOOKBACK_DAYS,
+ 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.ts
new file mode 100644
index 000000000000..66cc3241a65f
--- /dev/null
+++ b/nodejs/src/cdp/services/email-reputation/temporal/workflow.ts
@@ -0,0 +1,77 @@
+/**
+ * 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.ts
new file mode 100644
index 000000000000..8da50d506e4d
--- /dev/null
+++ b/nodejs/src/cdp/services/email-reputation/types.ts
@@ -0,0 +1,19 @@
+/** 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.ts
index 2722b462bafe..7bccfc24eba0 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -50,6 +50,7 @@ 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.ts
index 6072465ea18a..34c930e9d7d3 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -14,6 +14,7 @@ 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'
@@ -40,6 +41,7 @@ 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'
@@ -53,7 +55,7 @@ import { createSesRateLimiterValkeyPool } from './cdp/services/rate-limiter/rate
import { 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 { PluginServerService, PluginsServerConfig, RedisPool } from './types'
+import { HealthCheckResultOk, PluginServerService, PluginsServerConfig, RedisPool } from './types'
/**
* PluginServer handles CDP, logs, evaluation scheduler, and local-dev combined modes.
@@ -395,6 +397,34 @@ 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 created
serviceLoaders.push(() => {
const serverCommands = new ServerCommands(this.pubsub!)
diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts
index 1c30d3afa778..a2d069b36aa6 100644
--- a/nodejs/src/types.ts
+++ b/nodejs/src/types.ts
@@ -157,6 +157,7 @@ export interface PluginServerCapabilities {
cdpRerunWorker?: boolean
cdpHogflowScheduler?: boolean
cdpHogflowSubscriptionMatcher?: boolean
+ emailReputationEvaluator?: boolean
recordingApi?: boolean
ingestionV2Testing?: boolean
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ec8268d1e9d4..f40e7027f2da 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1582,6 +1582,9 @@ importers:
'@temporalio/worker':
specifier: 1.15.0
+ '@temporalio/workflow':
+ specifier: 1.15.0
+ version: 1.15.0
'@types/node':
specifier: 'catalog:'
version: 22.18.8