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(llma): add tagger scheduler matching and workflow dispatch (3/5) (#54590)

Andrew Maguire06a0f37a4f21
diff --git a/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts b/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts
index 96c40e7c5ad8..c08a36580416 100644
--- a/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts
+++ b/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts
@@ -1,8 +1,14 @@
import { Message } from 'node-rdkafka'
-import { createAiGenerationEvent, createEvaluation, createEvaluationCondition } from '~/llm-analytics/_tests/fixtures'
+import {
+ createAiGenerationEvent,
+ createEvaluation,
+ createEvaluationCondition,
+ createTagger,
+} from '~/llm-analytics/_tests/fixtures'
import { Hub } from '~/types'
import { closeHub, createHub } from '~/utils/db/hub'
+import { logger } from '~/utils/logger'
import {
EvaluationMatcher,
@@ -10,6 +16,7 @@ import {
checkRolloutPercentage,
filterAndParseMessages,
groupEventsByTeam,
+ unwrapOrLog,
} from './evaluation-scheduler'
jest.mock('~/llm-analytics/services/temporal.service')
@@ -364,5 +371,73 @@ describe('Evaluation Scheduler', () => {
})
)
})
+
+ it('matches taggers using the same Matchable contract as evaluations', async () => {
+ mockExecHog.mockResolvedValue({ execResult: { result: true } })
+
+ const event = createAiGenerationEvent(teamId)
+ const tagger = createTagger({
+ enabled: true,
+ conditions: [
+ createEvaluationCondition({ id: 'cond-1', rollout_percentage: 100, bytecode: ['_H', 1, 32, true] }),
+ ],
+ })
+
+ const result = await matcher.shouldTriggerEvaluation(event, tagger)
+
+ expect(result).toEqual({ matched: true, conditionId: 'cond-1' })
+ })
+
+ it('returns disabled for a disabled tagger without consulting bytecode', async () => {
+ const event = createAiGenerationEvent(teamId)
+ const tagger = createTagger({ enabled: false })
+
+ const result = await matcher.shouldTriggerEvaluation(event, tagger)
+
+ expect(result).toEqual({ matched: false, reason: 'disabled' })
+ expect(mockExecHog).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('unwrapOrLog', () => {
+ it('returns the value when the promise was fulfilled', () => {
+ const result = unwrapOrLog(
+ { status: 'fulfilled', value: { 1: ['a'], 2: ['b'] } } as PromiseSettledResult<
+ Record<string, string[]>
+ >,
+ 'should not log'
+ )
+
+ expect(result).toEqual({ 1: ['a'], 2: ['b'] })
+ })
+
+ it('returns an empty object and logs when rejected', () => {
+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => undefined)
+
+ const result = unwrapOrLog(
+ { status: 'rejected', reason: new Error('db down') } as PromiseSettledResult<Record<string, string[]>>,
+ 'fetch failed'
+ )
+
+ expect(result).toEqual({})
+ expect(errorSpy).toHaveBeenCalledWith('fetch failed', { error: 'db down' })
+
+ errorSpy.mockRestore()
+ })
+
+ it('coerces non-Error rejection reasons to string for the log payload', () => {
+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => undefined)
+
+ unwrapOrLog(
+ { status: 'rejected', reason: 'plain string failure' } as PromiseSettledResult<
+ Record<string, string[]>
+ >,
+ 'fetch failed'
+ )
+
+ expect(errorSpy).toHaveBeenCalledWith('fetch failed', { error: 'plain string failure' })
+
+ errorSpy.mockRestore()
+ })
})
})
diff --git a/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts b/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
index 356892e07883..5ba1b94b3f15 100644
--- a/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
+++ b/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
@@ -13,8 +13,9 @@ import { execHog } from '../cdp/utils/hog-exec'
import { KAFKA_EVENTS_JSON, prefix as KAFKA_PREFIX } from '../config/kafka-topics'
import { KafkaConsumer } from '../kafka/consumer'
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'
-import { Evaluation, EvaluationConditionSet } from '../llm-analytics/types'
+import { Evaluation, EvaluationConditionSet, Matchable, Tagger } from '../llm-analytics/types'
import { PluginServerService, RawKafkaEvent } from '../types'
import { PostgresRouter } from '../utils/db/postgres'
import { parseJSON } from '../utils/json-parse'
@@ -31,13 +32,13 @@ export interface EvaluationSchedulerDeps {
const evaluationSchedulerEventsProcessed = new Counter({
name: 'evaluation_scheduler_events_processed',
help: 'Number of AI events processed by evaluation scheduler',
- labelNames: ['status'],
+ labelNames: ['status', 'type'], // type: 'evaluation' | 'tagger' — keep existing eval alerts working while exposing tagger traffic
})
const evaluationMatchesCounter = new Counter({
name: 'evaluation_matches',
help: 'Number of evaluation matches by outcome',
- labelNames: ['outcome'], // matched, filtered, sampling_excluded, error
+ labelNames: ['outcome', 'type'], // matched, filtered, sampling_excluded, error × evaluation/tagger
})
const evaluationSchedulerMessagesReceived = new Counter({
@@ -59,6 +60,24 @@ const evaluationSchedulerHeaderValues = new Counter({
// Pure functions for testability
+/**
+ * Pull the value out of an awaited Promise.allSettled entry, falling back to an
+ * empty object map and logging the rejection reason. Used to keep the scheduler
+ * loop alive when one fetch fails without losing the other one's results.
+ */
+export function unwrapOrLog<T extends Record<string, unknown>>(
+ result: PromiseSettledResult<T>,
+ errorMessage: string
+): T {
+ if (result.status === 'fulfilled') {
+ return result.value
+ }
+ logger.error(errorMessage, {
+ error: result.reason instanceof Error ? result.reason.message : String(result.reason),
+ })
+ return {} as T
+}
+
export function filterAndParseMessages(messages: Message[]): RawKafkaEvent[] {
return messages
.filter((message) => {
@@ -175,12 +194,12 @@ export type EvaluationMatchResult =
| { matched: false; reason: 'no_conditions' | 'disabled' | 'filtered' | 'sampling_excluded' }
export class EvaluationMatcher {
- async shouldTriggerEvaluation(event: RawKafkaEvent, evaluation: Evaluation): Promise<EvaluationMatchResult> {
+ async shouldTriggerEvaluation(event: RawKafkaEvent, evaluation: Matchable): Promise<EvaluationMatchResult> {
if (!evaluation.enabled) {
return { matched: false, reason: 'disabled' }
}
- const conditions = evaluation.conditions as EvaluationConditionSet[]
+ const conditions = evaluation.conditions
if (conditions.length === 0) {
return { matched: false, reason: 'no_conditions' }
}
@@ -213,6 +232,7 @@ export const startEvaluationScheduler = async (
const temporalService = new TemporalService(config)
const evaluationManager = new EvaluationManagerService(deps.postgres, deps.pubSub)
+ const taggerManager = new TaggerManagerService(deps.postgres, deps.pubSub)
const kafkaConsumer = new KafkaConsumer({
groupId: `${KAFKA_PREFIX}evaluation-scheduler`,
@@ -220,7 +240,7 @@ export const startEvaluationScheduler = async (
})
await kafkaConsumer.connect((messages) =>
- eachBatchEvaluationScheduler(messages, evaluationManager, temporalService)
+ eachBatchEvaluationScheduler(messages, evaluationManager, taggerManager, temporalService)
)
const onShutdown = async () => {
@@ -238,6 +258,7 @@ export const startEvaluationScheduler = async (
async function eachBatchEvaluationScheduler(
messages: Message[],
evaluationManager: EvaluationManagerService,
+ taggerManager: TaggerManagerService,
temporalService: TemporalService
): Promise<void> {
logger.debug('Processing batch', { messageCount: messages.length })
@@ -264,14 +285,24 @@ async function eachBatchEvaluationScheduler(
const eventsByTeam = groupEventsByTeam(aiGenerationEvents)
const teamIds = Array.from(eventsByTeam.keys())
- const evaluationsByTeam = await evaluationManager.getEvaluationsForTeams(teamIds)
+ // Fetch evaluations and taggers independently — a transient DB failure on one
+ // side must not take down dispatch for the other. If either side fails we log
+ // and fall back to an empty map so the matched workflows just don't trigger
+ // this batch, instead of failing the whole Kafka consumer loop.
+ const [evaluationsResult, taggersResult] = await Promise.allSettled([
+ evaluationManager.getEvaluationsForTeams(teamIds),
+ taggerManager.getTaggersForTeams(teamIds),
+ ])
+ const evaluationsByTeam = unwrapOrLog(evaluationsResult, 'Failed to fetch evaluations for teams')
+ const taggersByTeam = unwrapOrLog(taggersResult, 'Failed to fetch taggers for teams')
const matcher = new EvaluationMatcher()
const tasks: Promise<void>[] = []
for (const [teamId, events] of eventsByTeam.entries()) {
const evaluationDefinitions = evaluationsByTeam[teamId] || []
+ const taggerDefinitions = taggersByTeam[teamId] || []
- if (evaluationDefinitions.length === 0) {
+ if (evaluationDefinitions.length === 0 && taggerDefinitions.length === 0) {
continue
}
@@ -284,7 +315,22 @@ async function eachBatchEvaluationScheduler(
eventUuid: event.uuid,
error: error instanceof Error ? error.message : String(error),
})
- evaluationMatchesCounter.labels({ outcome: 'error' }).inc()
+ evaluationMatchesCounter.labels({ outcome: 'error', type: 'evaluation' }).inc()
+ }
+ )
+
+ tasks.push(task)
+ }
+
+ for (const taggerDefinition of taggerDefinitions) {
+ const task = processEventTaggerMatch(event, taggerDefinition, matcher, temporalService).catch(
+ (error: unknown) => {
+ logger.error('Error processing tagger', {
+ taggerId: taggerDefinition.id,
+ eventUuid: event.uuid,
+ error: error instanceof Error ? error.message : String(error),
+ })
+ evaluationMatchesCounter.labels({ outcome: 'error', type: 'tagger' }).inc()
}
)
@@ -297,7 +343,7 @@ async function eachBatchEvaluationScheduler(
logger.debug('Batch processing complete', {
teamsProcessed: eventsByTeam.size,
- totalEvaluationChecks: tasks.length,
+ totalChecks: tasks.length,
})
}
@@ -307,12 +353,12 @@ async function processEventEvaluationMatch(
matcher: EvaluationMatcher,
temporalService: TemporalService
): Promise<void> {
- evaluationSchedulerEventsProcessed.labels({ status: 'received' }).inc()
+ evaluationSchedulerEventsProcessed.labels({ status: 'received', type: 'evaluation' }).inc()
const result = await matcher.shouldTriggerEvaluation(event, evaluationDefinition)
if (!result.matched) {
- evaluationMatchesCounter.labels({ outcome: result.reason }).inc()
+ evaluationMatchesCounter.labels({ outcome: result.reason, type: 'evaluation' }).inc()
return
}
@@ -322,12 +368,40 @@ async function processEventEvaluationMatch(
conditionId: result.conditionId,
})
- evaluationMatchesCounter.labels({ outcome: 'matched' }).inc()
+ evaluationMatchesCounter.labels({ outcome: 'matched', type: 'evaluation' }).inc()
await temporalService.startEvaluationRunWorkflow(
evaluationDefinition.id,
event,
evaluationDefinition.evaluation_type as string
)
- evaluationSchedulerEventsProcessed.labels({ status: 'success' }).inc()
+ evaluationSchedulerEventsProcessed.labels({ status: 'success', type: 'evaluation' }).inc()
+}
+
+async function processEventTaggerMatch(
+ event: RawKafkaEvent,
+ taggerDefinition: Tagger,
+ matcher: EvaluationMatcher,
+ temporalService: TemporalService
+): Promise<void> {
+ evaluationSchedulerEventsProcessed.labels({ status: 'received', type: 'tagger' }).inc()
+
+ // Taggers use the same conditions structure as evaluations
+ const result = await matcher.shouldTriggerEvaluation(event, taggerDefinition)
+
+ if (!result.matched) {
+ evaluationMatchesCounter.labels({ outcome: result.reason, type: 'tagger' }).inc()
+ return
+ }
+
+ logger.debug('Tagger matched, enqueueing tagger run', {
+ taggerId: taggerDefinition.id,
+ eventUuid: event.uuid,
+ conditionId: result.conditionId,
+ })
+
+ evaluationMatchesCounter.labels({ outcome: 'matched', type: 'tagger' }).inc()
+
+ await temporalService.startTaggerRunWorkflow(taggerDefinition.id, event)
+ evaluationSchedulerEventsProcessed.labels({ status: 'success', type: 'tagger' }).inc()
}
diff --git a/nodejs/src/llm-analytics/_tests/fixtures.ts b/nodejs/src/llm-analytics/_tests/fixtures.ts
index a7d5956dfd94..fac0e03a17e2 100644
--- a/nodejs/src/llm-analytics/_tests/fixtures.ts
+++ b/nodejs/src/llm-analytics/_tests/fixtures.ts
@@ -5,7 +5,7 @@ import { insertRow } from '~/tests/helpers/sql'
import { ClickHouseTimestamp, ProjectId, RawClickHouseEvent, Team } from '../../types'
import { PostgresRouter } from '../../utils/db/postgres'
-import { Evaluation, EvaluationConditionSet, EvaluationStatus } from '../types'
+import { Evaluation, EvaluationConditionSet, EvaluationStatus, Tagger } from '../types'
export const createEvaluation = (evaluation: Partial<Evaluation>): Evaluation => {
const enabled = evaluation.enabled !== undefined ? evaluation.enabled : true
@@ -63,6 +63,53 @@ export const insertEvaluation = async (
return res
}
+export const createTagger = (tagger: Partial<Tagger> = {}): Tagger => {
+ return {
+ id: randomUUID(),
+ team_id: 1,
+ name: 'Test Tagger',
+ enabled: tagger.enabled !== undefined ? tagger.enabled : true,
+ tagger_config: {
+ prompt: 'Tag this',
+ tags: [{ name: 'billing' }, { name: 'analytics' }],
+ min_tags: 0,
+ max_tags: 2,
+ },
+ conditions: [
+ {
+ id: 'condition-1',
+ rollout_percentage: 100,
+ properties: [],
+ },
+ ],
+ created_at: DateTime.now().toISO(),
+ updated_at: DateTime.now().toISO(),
+ ...tagger,
+ }
+}
+
+export const insertTagger = async (
+ postgres: PostgresRouter,
+ team_id: Team['id'],
+ tagger: Partial<Tagger> = {}
+): Promise<Tagger> => {
+ const created = createTagger({
+ ...tagger,
+ team_id,
+ })
+
+ const res = await insertRow(postgres, 'llm_analytics_tagger', {
+ ...created,
+ tagger_type: 'llm',
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ created_by_id: 1001,
+ deleted: false,
+ description: created.description || '',
+ })
+ return res
+}
+
export const createAiGenerationEvent = (teamId: number, data: Partial<RawClickHouseEvent> = {}): RawClickHouseEvent => {
return {
team_id: teamId,
diff --git a/nodejs/src/llm-analytics/services/tagger-manager.service.test.ts b/nodejs/src/llm-analytics/services/tagger-manager.service.test.ts
new file mode 100644
index 000000000000..f8691dcb8b4f
--- /dev/null
+++ b/nodejs/src/llm-analytics/services/tagger-manager.service.test.ts
@@ -0,0 +1,177 @@
+import { createTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'
+import { Hub } from '~/types'
+import { closeHub, createHub } from '~/utils/db/hub'
+import { PostgresUse } from '~/utils/db/postgres'
+
+import { insertTagger } from '../_tests/fixtures'
+import { Tagger } from '../types'
+import { TaggerManagerService } from './tagger-manager.service'
+
+describe('TaggerManagerService', () => {
+ jest.setTimeout(2000)
+ let hub: Hub
+ let manager: TaggerManagerService
+
+ let taggers: Tagger[]
+
+ let teamId1: number
+ let teamId2: number
+
+ beforeEach(async () => {
+ hub = await createHub()
+ await resetTestDatabase()
+ manager = new TaggerManagerService(hub.postgres, hub.pubSub)
+
+ const team = await getTeam(hub.postgres, 2)
+
+ teamId1 = await createTeam(hub.postgres, team!.organization_id)
+ teamId2 = await createTeam(hub.postgres, team!.organization_id)
+
+ taggers = []
+
+ taggers.push(
+ await insertTagger(hub.postgres, teamId1, {
+ name: 'Test Tagger team 1',
+ enabled: true,
+ })
+ )
+
+ taggers.push(
+ await insertTagger(hub.postgres, teamId1, {
+ name: 'Test Tagger team 1 - disabled',
+ enabled: false,
+ })
+ )
+
+ taggers.push(
+ await insertTagger(hub.postgres, teamId2, {
+ name: 'Test Tagger team 2',
+ enabled: true,
+ })
+ )
+ })
+
+ afterEach(async () => {
+ await closeHub(hub)
+ })
+
+ it('returns taggers for a team', async () => {
+ const items = await manager.getTaggersForTeam(teamId1)
+
+ expect(items).toHaveLength(1)
+ expect(items[0].id).toEqual(taggers[0].id)
+ expect(items[0].team_id).toEqual(teamId1)
+ expect(items[0].name).toEqual('Test Tagger team 1')
+ })
+
+ it('returns taggers for multiple teams in batch', async () => {
+ const result = await manager.getTaggersForTeams([teamId1, teamId2])
+
+ expect(result[teamId1]).toHaveLength(1)
+ expect(result[teamId2]).toHaveLength(1)
+ expect(result[teamId1][0].id).toEqual(taggers[0].id)
+ expect(result[teamId2][0].id).toEqual(taggers[2].id)
+ })
+
+ it('returns empty array for teams with no taggers', async () => {
+ const nonExistentTeamId = teamId2 + 1
+ const items = await manager.getTaggersForTeam(nonExistentTeamId)
+
+ expect(items).toEqual([])
+ })
+
+ it('filters out disabled taggers', async () => {
+ const items = await manager.getTaggersForTeam(teamId1)
+
+ expect(items).toHaveLength(1)
+ expect(items[0].id).toEqual(taggers[0].id)
+ })
+
+ it('filters out deleted taggers (detail-fetch guard)', async () => {
+ // Soft-delete the first tagger
+ await hub.postgres.query(
+ PostgresUse.COMMON_WRITE,
+ `UPDATE llm_analytics_tagger SET deleted = true, updated_at = NOW() WHERE id = $1`,
+ [taggers[0].id],
+ 'testKey'
+ )
+
+ // Force the manager to refetch (would normally be triggered by the post_save signal)
+ manager['onTaggersReloaded'](teamId1, [taggers[0].id])
+
+ const items = await manager.getTaggersForTeam(teamId1)
+ expect(items).toHaveLength(0)
+ })
+
+ it('caches taggers and uses cache on subsequent calls', async () => {
+ const items1 = await manager.getTaggersForTeam(teamId1)
+ expect(items1).toHaveLength(1)
+
+ await hub.postgres.query(
+ PostgresUse.COMMON_WRITE,
+ `UPDATE llm_analytics_tagger SET name = 'Updated Name', updated_at = NOW() WHERE id = $1`,
+ [taggers[0].id],
+ 'testKey'
+ )
+
+ const items2 = await manager.getTaggersForTeam(teamId1)
+ expect(items2).toHaveLength(1)
+ expect(items2[0].name).toEqual('Test Tagger team 1') // cached, not the updated value
+ })
+
+ it('reloads taggers when pubsub message received', async () => {
+ const itemsBefore = await manager.getTaggersForTeam(teamId1)
+ expect(itemsBefore).toHaveLength(1)
+
+ await hub.postgres.query(
+ PostgresUse.COMMON_WRITE,
+ `UPDATE llm_analytics_tagger SET name = 'Updated Tagger', updated_at = NOW() WHERE id = $1`,
+ [taggers[0].id],
+ 'testKey'
+ )
+
+ manager['onTaggersReloaded'](teamId1, [taggers[0].id])
+
+ const itemsAfter = await manager.getTaggersForTeam(teamId1)
+ expect(itemsAfter).toMatchObject([
+ {
+ id: taggers[0].id,
+ name: 'Updated Tagger',
+ },
+ ])
+ })
+
+ it('filters out tagger when disabled via reload (auto-disable path)', async () => {
+ const itemsBefore = await manager.getTaggersForTeam(teamId1)
+ expect(itemsBefore).toHaveLength(1)
+
+ await hub.postgres.query(
+ PostgresUse.COMMON_WRITE,
+ `UPDATE llm_analytics_tagger SET enabled = false, updated_at = NOW() WHERE id = $1`,
+ [taggers[0].id],
+ 'testKey'
+ )
+
+ manager['onTaggersReloaded'](teamId1, [taggers[0].id])
+
+ const itemsAfter = await manager.getTaggersForTeam(teamId1)
+ expect(itemsAfter).toHaveLength(0)
+ })
+
+ it('handles non-existent team IDs gracefully in batch fetch', async () => {
+ const nonExistentTeamId = teamId2 + 100
+ const result = await manager.getTaggersForTeams([teamId1, nonExistentTeamId, teamId2])
+
+ expect(result[teamId1]).toHaveLength(1)
+ expect(result[nonExistentTeamId]).toEqual([])
+ expect(result[teamId2]).toHaveLength(1)
+ })
+
+ it('exposes single-tagger getter that returns null for unknown ids', async () => {
+ const known = await manager.getTagger(taggers[0].id)
+ expect(known?.id).toEqual(taggers[0].id)
+
+ const unknown = await manager.getTagger('00000000-0000-0000-0000-000000000000')
+ expect(unknown).toBeNull()
+ })
+})
diff --git a/nodejs/src/llm-analytics/services/tagger-manager.service.ts b/nodejs/src/llm-analytics/services/tagger-manager.service.ts
new file mode 100644
index 000000000000..ad7399696458
--- /dev/null
+++ b/nodejs/src/llm-analytics/services/tagger-manager.service.ts
@@ -0,0 +1,131 @@
+import { Team } from '../../types'
+import { PostgresRouter, PostgresUse } from '../../utils/db/postgres'
+import { LazyLoader } from '../../utils/lazy-loader'
+import { logger } from '../../utils/logger'
+import { PubSub } from '../../utils/pubsub'
+import { Tagger, TaggerInfo } from '../types'
+
+const TAGGER_FIELDS = ['id', 'team_id', 'name', 'enabled', 'tagger_config', 'conditions', 'created_at', 'updated_at']
+
+export class TaggerManagerService {
+ private lazyLoader: LazyLoader<Tagger>
+ private lazyLoaderByTeam: LazyLoader<TaggerInfo[]>
+
+ constructor(
+ private postgres: PostgresRouter,
+ private pubSub: PubSub
+ ) {
+ this.lazyLoaderByTeam = new LazyLoader({
+ name: 'tagger_manager_by_team',
+ loader: async (teamIds) => await this.fetchTeamTaggers(teamIds),
+ })
+
+ this.lazyLoader = new LazyLoader({
+ name: 'tagger_manager',
+ loader: async (ids) => await this.fetchTaggers(ids),
+ })
+
+ this.pubSub.on<{ teamId: Team['id']; taggerIds: Tagger['id'][] }>('reload-taggers', ({ teamId, taggerIds }) => {
+ logger.debug('⚡', '[PubSub] Reloading taggers!', { teamId, taggerIds })
+ this.onTaggersReloaded(teamId, taggerIds)
+ })
+ }
+
+ public async getTaggersForTeam(teamId: Team['id']): Promise<Tagger[]> {
+ return (await this.getTaggersForTeams([teamId]))[teamId] ?? []
+ }
+
+ public async getTaggersForTeams(teamIds: Team['id'][]): Promise<Record<Team['id'], Tagger[]>> {
+ const result = teamIds.reduce<Record<Team['id'], Tagger[]>>((acc, teamId) => {
+ acc[teamId] = []
+ return acc
+ }, {})
+
+ const teamTaggerIds = await this.getTaggerIdsForTeams(teamIds)
+ const allTaggerIds = Object.values(teamTaggerIds).flat()
+ const taggers = await this.lazyLoader.getMany(allTaggerIds)
+
+ for (const tagger of Object.values(taggers)) {
+ if (!tagger) {
+ continue
+ }
+ result[tagger.team_id] = result[tagger.team_id] ?? []
+ result[tagger.team_id].push(tagger)
+ }
+
+ return result
+ }
+
+ public async getTaggerIdsForTeams(teamIds: Team['id'][]): Promise<Record<Team['id'], string[]>> {
+ const result = teamIds.reduce<Record<Team['id'], string[]>>((acc, teamId) => {
+ acc[teamId] = []
+ return acc
+ }, {})
+
+ const teamTaggers = await this.lazyLoaderByTeam.getMany(teamIds.map((x) => x.toString()))
+
+ if (!teamTaggers) {
+ return result
+ }
+
+ Object.entries(teamTaggers).forEach(([teamId, teamTags]) => {
+ if (teamTags) {
+ result[parseInt(teamId)] = teamTags.map((tagger) => tagger.id)
+ }
+ })
+
+ return result
+ }
+
+ public async getTagger(id: Tagger['id']): Promise<Tagger | null> {
+ return (await this.lazyLoader.get(id)) ?? null
+ }
+
+ private onTaggersReloaded(teamId: Team['id'], taggerIds: Tagger['id'][]): void {
+ this.lazyLoaderByTeam.markForRefresh(teamId.toString())
+ this.lazyLoader.markForRefresh(taggerIds)
+ }
+
+ private async fetchTeamTaggers(teamIds: string[]): Promise<Record<string, TaggerInfo[]>> {
+ logger.debug('[TaggerManager]', 'Fetching team taggers', { teamIds })
+ const response = await this.postgres.query<TaggerInfo>(
+ PostgresUse.COMMON_READ,
+ `SELECT id, team_id FROM llm_analytics_tagger WHERE enabled = TRUE AND deleted = FALSE AND team_id = ANY($1)`,
+ [teamIds],
+ 'fetchAllTeamTaggers'
+ )
+
+ const taggersByTeam: Record<string, TaggerInfo[]> = {}
+
+ for (const item of response.rows) {
+ const teamId = item.team_id.toString()
+ if (!taggersByTeam[teamId]) {
+ taggersByTeam[teamId] = []
+ }
+ taggersByTeam[teamId].push(item)
+ }
+
+ return taggersByTeam
+ }
+
+ private async fetchTaggers(ids: string[]): Promise<Record<string, Tagger | undefined>> {
+ logger.debug('[TaggerManager]', 'Fetching taggers', { ids })
+
+ // Filter deleted and disabled rows even though team-level discovery already
+ // filters — taggers can be soft-deleted or disabled between discovery and
+ // detail fetch, and we don't want to dispatch a run-tagger workflow for one.
+ const response = await this.postgres.query<Tagger>(
+ PostgresUse.COMMON_READ,
+ `SELECT ${TAGGER_FIELDS.join(', ')} FROM llm_analytics_tagger WHERE id = ANY($1) AND deleted = FALSE AND enabled = TRUE`,
+ [ids],
+ 'fetchTaggers'
+ )
+
+ const taggers = response.rows
+
+ return taggers.reduce<Record<string, Tagger | undefined>>((acc, tagger) => {
+ acc[tagger.id] = tagger
+ return acc
+ }, {})
+ }
+}
diff --git a/nodejs/src/llm-analytics/services/temporal.service.test.ts b/nodejs/src/llm-analytics/services/temporal.service.test.ts
index f4736fbbf220..775eb0f31ca0 100644
--- a/nodejs/src/llm-analytics/services/temporal.service.test.ts
+++ b/nodejs/src/llm-analytics/services/temporal.service.test.ts
@@ -162,5 +162,63 @@ describe('TemporalService', () => {
'Temporal unavailable'
)
})
+
+ it('starts tagger run workflow with correct parameters', async () => {
+ const mockEvent = createMockEvent({ properties: { $ai_input: 'test', $ai_output: 'response' } as any })
+
+ await service.startTaggerRunWorkflow('tagger-123', mockEvent)
+
+ expect(mockClient.workflow.start).toHaveBeenCalledWith('run-tagger', {
+ taskQueue: 'llm-analytics-evals-task-queue',
+ workflowId: 'llma-tagger-tagger-123-event-456-ingestion',
+ workflowIdConflictPolicy: 'USE_EXISTING',
+ workflowTaskTimeout: '2 minutes',
+ args: [
+ {
+ tagger_id: 'tagger-123',
+ event_data: mockEvent,
+ },
+ ],
+ })
+ })
+
+ it('generates deterministic tagger workflow IDs', async () => {
+ const mockEvent = createMockEvent()
+
+ await service.startTaggerRunWorkflow('tagger-123', mockEvent)
+ await service.startTaggerRunWorkflow('tagger-123', mockEvent)
+
+ const calls = (mockClient.workflow.start as jest.Mock).mock.calls
+ expect(calls[0][1].workflowId).toEqual(calls[1][1].workflowId)
+ expect(calls[0][1].workflowId).toBe('llma-tagger-tagger-123-event-456-ingestion')
+ })
+
+ it('generates different tagger workflow IDs for different events', async () => {
+ const mockEvent1 = createMockEvent({ uuid: 'event-1' })
+ const mockEvent2 = createMockEvent({ uuid: 'event-2' })
+
+ await service.startTaggerRunWorkflow('tagger-123', mockEvent1)
+ await service.startTaggerRunWorkflow('tagger-123', mockEvent2)
+
+ const calls = (mockClient.workflow.start as jest.Mock).mock.calls
+ expect(calls[0][1].workflowId).toBe('llma-tagger-tagger-123-event-1-ingestion')
+ expect(calls[1][1].workflowId).toBe('llma-tagger-tagger-123-event-2-ingestion')
+ })
+
+ it('tagger and evaluation share the same task queue', async () => {
+ await service.startEvaluationRunWorkflow('eval-1', createMockEvent({ uuid: 'e1' }))
+ await service.startTaggerRunWorkflow('tagger-1', createMockEvent({ uuid: 'e2' }))
+
+ const calls = (mockClient.workflow.start as jest.Mock).mock.calls
+ expect(calls[0][1].taskQueue).toEqual(calls[1][1].taskQueue)
+ })
+
+ it('throws on tagger workflow start failure', async () => {
+ ;(mockClient.workflow.start as jest.Mock).mockRejectedValue(new Error('Temporal unavailable'))
+
+ await expect(service.startTaggerRunWorkflow('tagger-123', createMockEvent())).rejects.toThrow(
+ 'Temporal unavailable'
+ )
+ })
})
})
diff --git a/nodejs/src/llm-analytics/services/temporal.service.ts b/nodejs/src/llm-analytics/services/temporal.service.ts
index 97b373fae675..c5f2321890f8 100644
--- a/nodejs/src/llm-analytics/services/temporal.service.ts
+++ b/nodejs/src/llm-analytics/services/temporal.service.ts
@@ -139,6 +139,36 @@ export class TemporalService {
return handle
}
+ async startTaggerRunWorkflow(taggerId: string, event: RawKafkaEvent): Promise<WorkflowHandle> {
+ const client = await this.ensureConnected()
+
+ const workflowId = `llma-tagger-${taggerId}-${event.uuid}-ingestion`
+
+ const handle = await client.workflow.start('run-tagger', {
+ args: [
+ {
+ tagger_id: taggerId,
+ event_data: event,
+ },
+ ],
+ taskQueue: EVALUATION_TASK_QUEUE,
+ workflowId,
+ workflowIdConflictPolicy: 'USE_EXISTING',
+ workflowTaskTimeout: '2 minutes',
+ })
+
+ temporalWorkflowsStarted.labels({ status: 'success' }).inc()
+
+ logger.debug('Started tagger run workflow', {
+ workflowId,
+ taggerId,
+ targetEventId: event.uuid,
+ timestamp: event.timestamp,
+ })
+
+ return handle
+ }
+
async disconnect(): Promise<void> {
if (this.client) {
await this.client.connection.close()
diff --git a/nodejs/src/llm-analytics/types.ts b/nodejs/src/llm-analytics/types.ts
index 1cd07eb578e3..4a1b4f8f5ed1 100644
--- a/nodejs/src/llm-analytics/types.ts
+++ b/nodejs/src/llm-analytics/types.ts
@@ -30,3 +30,28 @@ export interface EvaluationConditionSet {
}
export type EvaluationInfo = Pick<Evaluation, 'id' | 'team_id'>
+
+/** Shared interface for condition matching — used by both evaluations and taggers. */
+export interface Matchable {
+ enabled: boolean
+ conditions: EvaluationConditionSet[]
+}
+
+export interface Tagger {
+ id: string
+ team_id: number
+ name: string
+ description?: string
+ enabled: boolean
+ tagger_config: {
+ prompt: string
+ tags: { name: string; description?: string }[]
+ min_tags: number
+ max_tags: number | null
+ }
+ conditions: EvaluationConditionSet[]
+ created_at: string
+ updated_at: string
+}
+
+export type TaggerInfo = Pick<Tagger, 'id' | 'team_id'>