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.

fix(llma): route stripped teams to ai_events topic in eval scheduler (#58149)

Carlos Marchal36bf3078488d
diff --git a/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts b/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts
index c08a36580416..419e388ac5ba 100644
--- a/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts
+++ b/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts
@@ -1,11 +1,13 @@
import { Message } from 'node-rdkafka'
+import { parseTeamsList } from '~/ingestion/event-processing/split-ai-events-step'
import {
createAiGenerationEvent,
createEvaluation,
createEvaluationCondition,
createTagger,
} from '~/llm-analytics/_tests/fixtures'
+import { getDefaultLlmAnalyticsConfig } from '~/llm-analytics/config'
import { Hub } from '~/types'
import { closeHub, createHub } from '~/utils/db/hub'
import { logger } from '~/utils/logger'
@@ -14,8 +16,10 @@ import {
EvaluationMatcher,
checkConditionMatch,
checkRolloutPercentage,
+ eachBatchEvaluationScheduler,
filterAndParseMessages,
groupEventsByTeam,
+ teamShouldBeProcessed,
unwrapOrLog,
} from './evaluation-scheduler'
@@ -440,4 +444,148 @@ describe('Evaluation Scheduler', () => {
errorSpy.mockRestore()
})
})
+
+ describe('teamShouldBeProcessed', () => {
+ // Drives the partition between the two scheduler deployments. Both must read
+ // the same aiTopicTeams value or you get gap (some team handled by neither)
+ // or overlap (some team handled by both → broken results may cement).
+ const cases: Array<{
+ name: string
+ topic: 'events' | 'ai_events'
+ teams: number[] | '*'
+ teamId: number
+ expected: boolean
+ }> = [
+ { name: 'ai_events keeps team in list', topic: 'ai_events', teams: [2, 99], teamId: 2, expected: true },
+ {
+ name: 'ai_events drops team not in list',
+ topic: 'ai_events',
+ teams: [2, 99],
+ teamId: 7,
+ expected: false,
+ },
+ { name: 'events drops team in list', topic: 'events', teams: [2, 99], teamId: 2, expected: false },
+ { name: 'events keeps team not in list', topic: 'events', teams: [2, 99], teamId: 7, expected: true },
+ { name: 'ai_events keeps everything when *', topic: 'ai_events', teams: '*', teamId: 1234, expected: true },
+ { name: 'events drops everything when *', topic: 'events', teams: '*', teamId: 1234, expected: false },
+ {
+ name: 'ai_events drops everything when empty list',
+ topic: 'ai_events',
+ teams: [],
+ teamId: 2,
+ expected: false,
+ },
+ { name: 'events keeps everything when empty list', topic: 'events', teams: [], teamId: 2, expected: true },
+ ]
+
+ it.each(cases)('$name', ({ topic, teams, teamId, expected }) => {
+ expect(teamShouldBeProcessed(teamId, topic, teams)).toBe(expected)
+ })
+ })
+
+ describe('eachBatchEvaluationScheduler partitioning', () => {
+ const noopEvaluationManager = {
+ getEvaluationsForTeams: jest.fn().mockResolvedValue({}),
+ } as unknown as import('~/llm-analytics/services/evaluation-manager.service').EvaluationManagerService
+ const noopTaggerManager = {
+ getTaggersForTeams: jest.fn().mockResolvedValue({}),
+ } as unknown as import('~/llm-analytics/services/tagger-manager.service').TaggerManagerService
+ const noopTemporal = {} as unknown as import('~/llm-analytics/services/temporal.service').TemporalService
+
+ beforeEach(() => {
+ ;(noopEvaluationManager.getEvaluationsForTeams as jest.Mock).mockClear()
+ ;(noopTaggerManager.getTaggersForTeams as jest.Mock).mockClear()
+ })
+
+ const messageFor = (teamIdForEvent: number): Message =>
+ ({
+ headers: [{ productTrack: Buffer.from('llma') }],
+ value: Buffer.from(JSON.stringify(createAiGenerationEvent(teamIdForEvent))),
+ }) as any
+
+ it('ai_events deployment only fetches definitions for teams in the list', async () => {
+ await eachBatchEvaluationScheduler(
+ [messageFor(2), messageFor(7), messageFor(99)],
+ noopEvaluationManager,
+ noopTaggerManager,
+ noopTemporal,
+ { topic: 'ai_events', aiTopicTeams: [2, 99] }
+ )
+
+ expect(noopEvaluationManager.getEvaluationsForTeams).toHaveBeenCalledTimes(1)
+ const teamsAsked = (noopEvaluationManager.getEvaluationsForTeams as jest.Mock).mock.calls[0][0] as number[]
+ expect(teamsAsked.sort()).toEqual([2, 99])
+ })
+
+ it('events deployment only fetches definitions for teams NOT in the list', async () => {
+ await eachBatchEvaluationScheduler(
+ [messageFor(2), messageFor(7), messageFor(99)],
+ noopEvaluationManager,
+ noopTaggerManager,
+ noopTemporal,
+ { topic: 'events', aiTopicTeams: [2, 99] }
+ )
+
+ expect(noopEvaluationManager.getEvaluationsForTeams).toHaveBeenCalledTimes(1)
+ const teamsAsked = (noopEvaluationManager.getEvaluationsForTeams as jest.Mock).mock.calls[0][0] as number[]
+ expect(teamsAsked).toEqual([7])
+ })
+
+ it('skips Postgres entirely when partition drops every event', async () => {
+ await eachBatchEvaluationScheduler(
+ [messageFor(7), messageFor(8)],
+ noopEvaluationManager,
+ noopTaggerManager,
+ noopTemporal,
+ { topic: 'ai_events', aiTopicTeams: [2, 99] }
+ )
+
+ expect(noopEvaluationManager.getEvaluationsForTeams).not.toHaveBeenCalled()
+ expect(noopTaggerManager.getTaggersForTeams).not.toHaveBeenCalled()
+ })
+
+ // Locks down the contract that gates the deploy ordering: a deployment
+ // running the new image with neither LLMA_EVAL_SCHEDULER_TOPIC nor
+ // LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS set in env behaves identically to
+ // the legacy events-only consumer. This is what lets us land the new
+ // image into state.yaml before any chart override is applied without
+ // any risk of accidental traffic divergence.
+ describe('default config preserves legacy behavior', () => {
+ it('exposes "events" topic and empty team list as defaults', () => {
+ const defaults = getDefaultLlmAnalyticsConfig()
+ expect(defaults.LLMA_EVAL_SCHEDULER_TOPIC).toBe('events')
+ expect(defaults.LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS).toBe('')
+ })
+
+ it('parsed defaults yield empty team list (not "*"), so events-mode processes everyone', () => {
+ const defaults = getDefaultLlmAnalyticsConfig()
+ const parsed = parseTeamsList(defaults.LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS)
+ expect(parsed).toEqual([])
+ expect(teamShouldBeProcessed(2, defaults.LLMA_EVAL_SCHEDULER_TOPIC, parsed)).toBe(true)
+ expect(teamShouldBeProcessed(385921, defaults.LLMA_EVAL_SCHEDULER_TOPIC, parsed)).toBe(true)
+ expect(teamShouldBeProcessed(7, defaults.LLMA_EVAL_SCHEDULER_TOPIC, parsed)).toBe(true)
+ })
+
+ it('eachBatchEvaluationScheduler with parsed defaults processes every team in the batch', async () => {
+ const defaults = getDefaultLlmAnalyticsConfig()
+ const partition = {
+ topic: defaults.LLMA_EVAL_SCHEDULER_TOPIC,
+ aiTopicTeams: parseTeamsList(defaults.LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS),
+ }
+
+ await eachBatchEvaluationScheduler(
+ [messageFor(2), messageFor(7), messageFor(385921), messageFor(99)],
+ noopEvaluationManager,
+ noopTaggerManager,
+ noopTemporal,
+ partition
+ )
+
+ expect(noopEvaluationManager.getEvaluationsForTeams).toHaveBeenCalledTimes(1)
+ const teamsAsked = (noopEvaluationManager.getEvaluationsForTeams as jest.Mock).mock
+ .calls[0][0] as number[]
+ expect(teamsAsked.sort((a, b) => a - b)).toEqual([2, 7, 99, 385921])
+ })
+ })
+ })
})
diff --git a/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts b/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
index e165fcd976ef..160a5e265d5c 100644
--- a/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
+++ b/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
@@ -1,17 +1,34 @@
/**
* Evaluation Scheduler
*
- * Consumes AI events (e.g., $ai_generation) from the main events stream,
- * matches them against evaluation filters, and triggers evaluation workflows
- * via Temporal when conditions are met.
+ * Consumes AI events (e.g., $ai_generation) from a Kafka topic, matches them
+ * against evaluation filters, and triggers evaluation workflows via Temporal
+ * when conditions are met.
+ *
+ * Two deployments run in parallel during the AI events table rollout, each
+ * reading a different topic and partitioning teams between them via
+ * LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS:
+ *
+ * - topic=events → reads clickhouse_events_json, processes teams NOT in the list.
+ * - topic=ai_events → reads clickhouse_ai_events_json, processes teams IN the list.
+ *
+ * The events topic strips heavy AI properties for teams in the strip-heavy
+ * rollout, which would leave the judge grading empty input/output. Routing
+ * those teams to the ai_events topic gets the unstripped payload.
+ *
+ * The two deployments cannot double-fire: the same (evaluation_id, event_uuid)
+ * yields the same Temporal workflow ID with USE_EXISTING — but the per-team
+ * partition makes that a backstop, not the primary correctness mechanism.
*/
import * as crypto from 'crypto'
import { Message } from 'node-rdkafka'
import { Counter } from 'prom-client'
import { execHog } from '../cdp/utils/hog-exec'
-import { KAFKA_EVENTS_JSON, prefix as KAFKA_PREFIX } from '../config/kafka-topics'
+import { KAFKA_CLICKHOUSE_AI_EVENTS_JSON, KAFKA_EVENTS_JSON, prefix as KAFKA_PREFIX } from '../config/kafka-topics'
+import { parseTeamsList } from '../ingestion/event-processing/split-ai-events-step'
import { createKafkaConsumer } from '../kafka/consumer'
+import { LlmAnalyticsConfig } from '../llm-analytics/config'
import { EvaluationManagerService } from '../llm-analytics/services/evaluation-manager.service'
import { TaggerManagerService } from '../llm-analytics/services/tagger-manager.service'
import { TemporalService, TemporalServiceConfig } from '../llm-analytics/services/temporal.service'
@@ -22,7 +39,8 @@ import { parseJSON } from '../utils/json-parse'
import { logger } from '../utils/logger'
import { PubSub } from '../utils/pubsub'
-export type EvaluationSchedulerConfig = TemporalServiceConfig
+export type EvaluationSchedulerConfig = TemporalServiceConfig &
+ Pick<LlmAnalyticsConfig, 'LLMA_EVAL_SCHEDULER_TOPIC' | 'LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS'>
export interface EvaluationSchedulerDeps {
postgres: PostgresRouter
@@ -58,6 +76,12 @@ const evaluationSchedulerHeaderValues = new Counter({
labelNames: ['header_value'],
})
+const evaluationSchedulerTeamPartition = new Counter({
+ name: 'evaluation_scheduler_team_partition',
+ help: 'Events kept vs dropped by the team partition filter',
+ labelNames: ['outcome'], // kept | dropped
+})
+
// Pure functions for testability
/**
@@ -78,6 +102,29 @@ export function unwrapOrLog<T extends Record<string, unknown>>(
return {} as T
}
+/**
+ * Returns true if the given team should be processed by this deployment. Mode
+ * is implicit from the topic: ai_events processes teams in the list, events
+ * processes teams not in the list. The two deployments must read the same
+ * `aiTopicTeams` value or you get either gap (some team handled by neither) or
+ * overlap (some team handled by both → broken results may cement via Temporal
+ * USE_EXISTING dedup before correct ones arrive). '*' is the final-state
+ * migration: every team has moved to ai_events and the events deployment
+ * becomes a no-op.
+ */
+export function teamShouldBeProcessed(
+ teamId: number,
+ topic: 'events' | 'ai_events',
+ aiTopicTeams: number[] | '*'
+): boolean {
+ const isAiTopicConsumer = topic === 'ai_events'
+ if (aiTopicTeams === '*') {
+ return isAiTopicConsumer
+ }
+ const inList = aiTopicTeams.includes(teamId)
+ return isAiTopicConsumer ? inList : !inList
+}
+
export function filterAndParseMessages(messages: Message[]): RawKafkaEvent[] {
return messages
.filter((message) => {
@@ -228,19 +275,39 @@ export const startEvaluationScheduler = async (
config: EvaluationSchedulerConfig,
deps: EvaluationSchedulerDeps
): Promise<PluginServerService> => {
- logger.info('🤖', 'Starting evaluation scheduler')
+ const topic = config.LLMA_EVAL_SCHEDULER_TOPIC
+ if (topic !== 'events' && topic !== 'ai_events') {
+ throw new Error(`Invalid LLMA_EVAL_SCHEDULER_TOPIC: ${topic as string}. Must be 'events' or 'ai_events'.`)
+ }
+ const aiTopicTeams = parseTeamsList(config.LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS)
+ // Distinct group id per topic so the two deployments never share offsets.
+ // The events-topic group id is unchanged (no suffix) so the existing
+ // production consumer keeps its committed offsets across this deploy.
+ const groupId =
+ topic === 'ai_events' ? `${KAFKA_PREFIX}evaluation-scheduler-ai-events` : `${KAFKA_PREFIX}evaluation-scheduler`
+ const kafkaTopic = topic === 'ai_events' ? KAFKA_CLICKHOUSE_AI_EVENTS_JSON : KAFKA_EVENTS_JSON
+
+ logger.info('🤖', 'Starting evaluation scheduler', {
+ topic,
+ groupId,
+ kafkaTopic,
+ aiTopicTeams: aiTopicTeams === '*' ? '*' : aiTopicTeams.join(','),
+ })
const temporalService = new TemporalService(config)
const evaluationManager = new EvaluationManagerService(deps.postgres, deps.pubSub)
const taggerManager = new TaggerManagerService(deps.postgres, deps.pubSub)
const kafkaConsumer = createKafkaConsumer({
- groupId: `${KAFKA_PREFIX}evaluation-scheduler`,
- topic: KAFKA_EVENTS_JSON,
+ groupId,
+ topic: kafkaTopic,
})
await kafkaConsumer.connect((messages) =>
- eachBatchEvaluationScheduler(messages, evaluationManager, taggerManager, temporalService)
+ eachBatchEvaluationScheduler(messages, evaluationManager, taggerManager, temporalService, {
+ topic,
+ aiTopicTeams,
+ })
)
const onShutdown = async () => {
@@ -255,11 +322,17 @@ export const startEvaluationScheduler = async (
}
}
-async function eachBatchEvaluationScheduler(
+export interface EachBatchPartitionConfig {
+ topic: 'events' | 'ai_events'
+ aiTopicTeams: number[] | '*'
+}
+
+export async function eachBatchEvaluationScheduler(
messages: Message[],
evaluationManager: EvaluationManagerService,
taggerManager: TaggerManagerService,
- temporalService: TemporalService
+ temporalService: TemporalService,
+ partition: EachBatchPartitionConfig
): Promise<void> {
logger.debug('Processing batch', { messageCount: messages.length })
@@ -270,19 +343,28 @@ async function eachBatchEvaluationScheduler(
evaluationSchedulerEventsFiltered.labels({ passed: 'false' }).inc(messages.length - aiGenerationEvents.length)
evaluationSchedulerEventsFiltered.labels({ passed: 'true' }).inc(aiGenerationEvents.length)
+ // Apply the team partition before any Postgres lookups. Counterpart deployment
+ // (other topic) is responsible for everything we drop here.
+ const partitionedEvents = aiGenerationEvents.filter((event) => {
+ const keep = teamShouldBeProcessed(event.team_id, partition.topic, partition.aiTopicTeams)
+ evaluationSchedulerTeamPartition.labels({ outcome: keep ? 'kept' : 'dropped' }).inc()
+ return keep
+ })
+
logger.debug('Filtered batch', {
totalMessages: messages.length,
aiEventsFound: aiGenerationEvents.length,
+ afterTeamPartition: partitionedEvents.length,
filteredOut: messages.length - aiGenerationEvents.length,
})
- if (aiGenerationEvents.length === 0) {
+ if (partitionedEvents.length === 0) {
return
}
- logger.debug('Found $ai_generation events', { count: aiGenerationEvents.length })
+ logger.debug('Found $ai_generation events', { count: partitionedEvents.length })
- const eventsByTeam = groupEventsByTeam(aiGenerationEvents)
+ const eventsByTeam = groupEventsByTeam(partitionedEvents)
const teamIds = Array.from(eventsByTeam.keys())
// Fetch evaluations and taggers independently — a transient DB failure on one
diff --git a/nodejs/src/ingestion/event-processing/split-ai-events-step.ts b/nodejs/src/ingestion/event-processing/split-ai-events-step.ts
index 771e14ee829e..feadfc18a0bb 100644
--- a/nodejs/src/ingestion/event-processing/split-ai-events-step.ts
+++ b/nodejs/src/ingestion/event-processing/split-ai-events-step.ts
@@ -85,7 +85,7 @@ function maybeStripAiProperties(
]
}
-function parseTeamsList(teamsStr: string): number[] | '*' {
+export function parseTeamsList(teamsStr: string): number[] | '*' {
if (teamsStr === '*') {
return '*'
}
diff --git a/nodejs/src/llm-analytics/config.ts b/nodejs/src/llm-analytics/config.ts
index 533d7f605f59..866adf37fa65 100644
--- a/nodejs/src/llm-analytics/config.ts
+++ b/nodejs/src/llm-analytics/config.ts
@@ -6,6 +6,18 @@ export type LlmAnalyticsConfig = {
TEMPORAL_CLIENT_ROOT_CA: string | undefined
TEMPORAL_CLIENT_CERT: string | undefined
TEMPORAL_CLIENT_KEY: string | undefined
+
+ // Topic the evaluation scheduler reads from. 'events' is the legacy shared
+ // events topic; 'ai_events' is the AI-only topic which carries the
+ // unstripped payload required for teams that have heavy props stripped from
+ // the events topic. Two scheduler deployments run in parallel during the
+ // rollout: one on each topic, partitioning teams between them via
+ // LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS — the AI-events deployment processes
+ // teams in that list, the events deployment processes everything else.
+ // Must be a superset of the strip-heavy team list, otherwise evals and
+ // taggers silently break for teams in the difference set (status quo bug).
+ LLMA_EVAL_SCHEDULER_TOPIC: 'events' | 'ai_events'
+ LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS: string
}
export function getDefaultLlmAnalyticsConfig(): LlmAnalyticsConfig {
@@ -16,5 +28,7 @@ export function getDefaultLlmAnalyticsConfig(): LlmAnalyticsConfig {
TEMPORAL_CLIENT_ROOT_CA: undefined,
TEMPORAL_CLIENT_CERT: undefined,
TEMPORAL_CLIENT_KEY: undefined,
+ LLMA_EVAL_SCHEDULER_TOPIC: 'events',
+ LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS: '',
}
}