:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(llma): trace-level evaluations (#66030)
Carlos Marchald7655378bb42
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 2d691d8a0de3..40f2ac2a035f 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -244,6 +244,9 @@ export const FEATURE_FLAGS = {ACTION_REFERENCE_COUNT: 'action-reference-count', // owner: @andyzzhao #team-product-analytics, gates bulk action reference counting on actions listADVANCE_MARKETING_ANALYTICS_SETTINGS: 'advance-marketing-analytics-settings', // owner: @jabahamondes #team-web-analyticsAI_GATEWAY: 'ai-gateway', // owner: #team-ai-gateway, gates the AI gateway UI and llm_gateway:read on project secret API keys+ AI_OBSERVABILITY_EVALUATIONS_TRACE_TARGET: 'ai-observability-evaluations-trace-target', // owner: #team-ai-observability+ /** Alert edit modal: check history chart + chart/table toggle (table remains when off). */+ ALERTS_15_MINUTE_INTERVAL: 'alerts-15-minute-interval', // owner: #team-analytics-platform, gates 15-minute insight alert intervalALERTS_ANOMALY_DETECTION: 'alerts-anomaly-detection', // owner: @andrewm4894ALERTS_INLINE_NOTIFICATIONS: 'alerts-inline-notifications', // owner: @vdekrijgerALERTS_INVESTIGATION_AGENT: 'alerts-investigation-agent', // owner: @andrewm4894, anomaly alerts — investigation agent on firingdiff --git a/nodejs/src/ai-observability/_tests/fixtures.ts b/nodejs/src/ai-observability/_tests/fixtures.tsindex e3e7fcafaef1..fead960c450f 100644--- a/nodejs/src/ai-observability/_tests/fixtures.ts+++ b/nodejs/src/ai-observability/_tests/fixtures.ts@@ -28,6 +28,8 @@ export const createEvaluation = (evaluation: Partial<Evaluation>): Evaluation =>properties: [],},],+ target: 'generation',+ target_config: {},created_at: DateTime.now().toISO(),updated_at: DateTime.now().toISO(),...evaluation,diff --git a/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.test.ts b/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.test.tsindex 40476dda7040..2444f35753bd 100644--- a/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.test.ts+++ b/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.test.ts@@ -13,6 +13,7 @@ import {checkConditionMatch,checkRolloutPercentage,eachBatchEvaluationScheduler,+ extractTraceContext,filterAndParseMessages,groupEventsByTeam,unwrapOrLog,@@ -439,6 +440,174 @@ describe('Evaluation Scheduler', () => {})})+ describe('extractTraceContext', () => {+ it('extracts string trace and session ids', () => {+ const event = createAiGenerationEvent(teamId, {+ properties: JSON.stringify({ $ai_trace_id: 'trace-1', $session_id: 'session-1' }),+ })++ expect(extractTraceContext(event)).toEqual({ traceId: 'trace-1', sessionId: 'session-1' })+ })++ it('coerces numeric trace ids to strings', () => {+ const event = createAiGenerationEvent(teamId, {+ properties: JSON.stringify({ $ai_trace_id: 0 }),+ })++ expect(extractTraceContext(event)).toEqual({ traceId: '0', sessionId: null })+ })++ it('returns nulls for missing or empty ids', () => {+ const event = createAiGenerationEvent(teamId, {+ properties: JSON.stringify({ $ai_trace_id: '', $ai_input: 'hi' }),+ })++ expect(extractTraceContext(event)).toEqual({ traceId: null, sessionId: null })+ })++ it('returns nulls on malformed properties JSON', () => {+ const event = createAiGenerationEvent(teamId, { properties: 'not json{' })++ expect(extractTraceContext(event)).toEqual({ traceId: null, sessionId: null })+ })+ })++ describe('EvaluationMatcher sampling key', () => {+ let mockExecHog: jest.Mock++ beforeEach(() => {+ mockExecHog = require('~/cdp/utils/hog-exec').execHog as jest.Mock+ mockExecHog.mockResolvedValue({ execResult: { result: true } })+ })++ it('samples on the provided key instead of the event uuid', async () => {+ const matcher = new EvaluationMatcher()+ const evaluation = createEvaluation({+ conditions: [createEvaluationCondition({ bytecode: ['_H', 1, 32, true], rollout_percentage: 50 })],+ })+ const keys = Array.from({ length: 100 }, (_, i) => `trace-${i}`)+ const includedKey = keys.find((key) => checkRolloutPercentage(key, 50))!+ const excludedKey = keys.find((key) => !checkRolloutPercentage(key, 50))!+ const event = createAiGenerationEvent(teamId)++ const includedResult = await matcher.shouldTriggerEvaluation(event, evaluation, includedKey)+ const excludedResult = await matcher.shouldTriggerEvaluation(event, evaluation, excludedKey)++ expect(includedResult.matched).toBe(true)+ expect(excludedResult.matched).toBe(false)+ })+ })++ describe('eachBatchEvaluationScheduler trace-target evaluations', () => {+ let mockExecHog: jest.Mock+ let evaluationManager: import('~/ai-observability/services/evaluation-manager.service').EvaluationManagerService+ let taggerManager: import('~/ai-observability/services/tagger-manager.service').TaggerManagerService+ let temporalService: import('~/ai-observability/services/temporal.service').TemporalService++ const messageFor = (event: ReturnType<typeof createAiGenerationEvent>): Message =>+ ({+ headers: [{ productTrack: Buffer.from('llma') }],+ value: Buffer.from(JSON.stringify(event)),+ }) as any++ beforeEach(() => {+ mockExecHog = require('~/cdp/utils/hog-exec').execHog as jest.Mock+ mockExecHog.mockResolvedValue({ execResult: { result: true } })++ evaluationManager = {+ getEvaluationsForTeams: jest.fn().mockResolvedValue({}),+ } as unknown as import('~/ai-observability/services/evaluation-manager.service').EvaluationManagerService+ taggerManager = {+ getTaggersForTeams: jest.fn().mockResolvedValue({}),+ } as unknown as import('~/ai-observability/services/tagger-manager.service').TaggerManagerService+ temporalService = {+ startEvaluationRunWorkflow: jest.fn().mockResolvedValue(undefined),+ startTraceEvaluationRunWorkflow: jest.fn().mockResolvedValue(undefined),+ startTaggerRunWorkflow: jest.fn().mockResolvedValue(undefined),+ } as unknown as import('~/ai-observability/services/temporal.service').TemporalService+ })++ it('dispatches the trace workflow with trace context and the config window', async () => {+ const event = createAiGenerationEvent(teamId, {+ properties: JSON.stringify({ $ai_trace_id: 'trace-1', $session_id: 'session-1' }),+ })+ const evaluation = createEvaluation({+ team_id: teamId,+ target: 'trace',+ target_config: { window_seconds: 90 },+ conditions: [createEvaluationCondition({ bytecode: ['_H', 1, 32, true], rollout_percentage: 100 })],+ })+ ;(evaluationManager.getEvaluationsForTeams as jest.Mock).mockResolvedValue({ [teamId]: [evaluation] })++ await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService)++ expect(temporalService.startTraceEvaluationRunWorkflow).toHaveBeenCalledWith(+ evaluation.id,+ event,+ 'trace-1',+ 'session-1',+ 90+ )+ expect(temporalService.startEvaluationRunWorkflow).not.toHaveBeenCalled()+ })++ it('falls back to the default window when target_config has none', async () => {+ const event = createAiGenerationEvent(teamId, {+ properties: JSON.stringify({ $ai_trace_id: 'trace-1' }),+ })+ const evaluation = createEvaluation({+ team_id: teamId,+ target: 'trace',+ target_config: {},+ conditions: [createEvaluationCondition({ bytecode: ['_H', 1, 32, true], rollout_percentage: 100 })],+ })+ ;(evaluationManager.getEvaluationsForTeams as jest.Mock).mockResolvedValue({ [teamId]: [evaluation] })++ await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService)++ const call = (temporalService.startTraceEvaluationRunWorkflow as jest.Mock).mock.calls[0]+ expect(call[4]).toBe(30 * 60)+ })++ it('skips trace-target evaluations when the event carries no trace id', async () => {+ const event = createAiGenerationEvent(teamId, {+ properties: JSON.stringify({ $ai_input: 'hi' }),+ })+ const evaluation = createEvaluation({+ team_id: teamId,+ target: 'trace',+ conditions: [createEvaluationCondition({ bytecode: ['_H', 1, 32, true], rollout_percentage: 100 })],+ })+ ;(evaluationManager.getEvaluationsForTeams as jest.Mock).mockResolvedValue({ [teamId]: [evaluation] })++ await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService)++ expect(temporalService.startTraceEvaluationRunWorkflow).not.toHaveBeenCalled()+ expect(temporalService.startEvaluationRunWorkflow).not.toHaveBeenCalled()+ })++ it('keeps dispatching the per-generation workflow for generation-target evaluations', async () => {+ const event = createAiGenerationEvent(teamId, {+ properties: JSON.stringify({ $ai_trace_id: 'trace-1' }),+ })+ const evaluation = createEvaluation({+ team_id: teamId,+ target: 'generation',+ conditions: [createEvaluationCondition({ bytecode: ['_H', 1, 32, true], rollout_percentage: 100 })],+ })+ ;(evaluationManager.getEvaluationsForTeams as jest.Mock).mockResolvedValue({ [teamId]: [evaluation] })++ await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService)++ expect(temporalService.startEvaluationRunWorkflow).toHaveBeenCalledWith(+ evaluation.id,+ event,+ evaluation.evaluation_type+ )+ expect(temporalService.startTraceEvaluationRunWorkflow).not.toHaveBeenCalled()+ })+ })+describe('eachBatchEvaluationScheduler batching', () => {const noopEvaluationManager = {getEvaluationsForTeams: jest.fn().mockResolvedValue({}),diff --git a/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.ts b/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.tsindex 8c930d5cf175..48223f13654f 100644--- a/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.ts+++ b/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.ts@@ -18,6 +18,7 @@ import { EvaluationManagerService } from '~/ai-observability/services/evaluationimport { ProviderKeyManagerService } from '~/ai-observability/services/provider-key-manager.service'import { TaggerManagerService } from '~/ai-observability/services/tagger-manager.service'import {+ DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS,TemporalService,TemporalServiceConfig,isEvaluationWorkflowRuntime,@@ -121,6 +122,26 @@ export function groupEventsByTeam(events: RawKafkaEvent[]): Map<number, RawKafkareturn grouped}+/**+ * Pull the trace linkage out of an event's properties. Trace ids are user-controlled and can+ * be ingested as numbers (e.g. a buggy `trace_id: 0`), so values are string-coerced; empty or+ * missing ids resolve to null.+ */+export function extractTraceContext(event: RawKafkaEvent): { traceId: string | null; sessionId: string | null } {+ let properties: Record<string, unknown> = {}+ try {+ properties = parseJSON(event.properties || '{}')+ } catch {+ return { traceId: null, sessionId: null }+ }+ const coerce = (value: unknown): string | null =>+ value === null || value === undefined || value === '' ? null : String(value)+ return {+ traceId: coerce(properties['$ai_trace_id']),+ sessionId: coerce(properties['$session_id']),+ }+}+export function checkRolloutPercentage(eventId: string, rolloutPercentage: number): boolean {if (rolloutPercentage >= 100) {return true@@ -205,7 +226,16 @@ export type EvaluationMatchResult =| { matched: false; reason: 'no_conditions' | 'disabled' | 'filtered' | 'sampling_excluded' }export class EvaluationMatcher {- async shouldTriggerEvaluation(event: RawKafkaEvent, evaluation: Matchable): Promise<EvaluationMatchResult> {+ /**+ * `samplingKey` defaults to the event uuid (independent coin flip per generation). Trace-+ * target evals pass the trace id instead so the whole trace is atomically in or out of the+ * sample, no matter which of its generations is seen first.+ */+ async shouldTriggerEvaluation(+ event: RawKafkaEvent,+ evaluation: Matchable,+ samplingKey?: string+ ): Promise<EvaluationMatchResult> {if (!evaluation.enabled) {return { matched: false, reason: 'disabled' }}@@ -222,7 +252,7 @@ export class EvaluationMatcher {continue}- const inSample = checkRolloutPercentage(event.uuid, condition.rollout_percentage)+ const inSample = checkRolloutPercentage(samplingKey ?? event.uuid, condition.rollout_percentage)if (!inSample) {continue@@ -409,7 +439,21 @@ async function processEventEvaluationMatch(): Promise<void> {evaluationSchedulerEventsProcessed.labels({ status: 'received', type: 'evaluation' }).inc()- const result = await matcher.shouldTriggerEvaluation(event, evaluationDefinition)+ const isTraceTarget = evaluationDefinition.target === 'trace'+ let traceContext: ReturnType<typeof extractTraceContext> | null = null+ if (isTraceTarget) {+ traceContext = extractTraceContext(event)+ if (!traceContext.traceId) {+ evaluationMatchesCounter.labels({ outcome: 'no_trace_id', type: 'evaluation' }).inc()+ return+ }+ }++ const result = await matcher.shouldTriggerEvaluation(+ event,+ evaluationDefinition,+ traceContext?.traceId ?? undefined+ )if (!result.matched) {evaluationMatchesCounter.labels({ outcome: result.reason, type: 'evaluation' }).inc()@@ -425,17 +469,32 @@ async function processEventEvaluationMatch(logger.debug('Evaluation matched, enqueueing evaluation run', {evaluationId: evaluationDefinition.id,eventUuid: event.uuid,+ traceId: traceContext?.traceId,conditionId: result.conditionId,})evaluationMatchesCounter.labels({ outcome: 'matched', type: 'evaluation' }).inc()- const evaluationRuntime = evaluationDefinition.evaluation_type- if (!isEvaluationWorkflowRuntime(evaluationRuntime)) {- throw new Error(`Unsupported evaluation runtime: ${evaluationRuntime}`)- }+ if (isTraceTarget && traceContext?.traceId) {+ // No isEvaluationWorkflowRuntime guard here: the trace workflow validates evaluation_type+ // server-side and rejects unsupported types as a non-retryable ApplicationError.+ const windowSeconds =+ evaluationDefinition.target_config?.window_seconds ?? DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS+ await temporalService.startTraceEvaluationRunWorkflow(+ evaluationDefinition.id,+ event,+ traceContext.traceId,+ traceContext.sessionId,+ windowSeconds+ )+ } else {+ const evaluationRuntime = evaluationDefinition.evaluation_type+ if (!isEvaluationWorkflowRuntime(evaluationRuntime)) {+ throw new Error(`Unsupported evaluation runtime: ${evaluationRuntime}`)+ }- await temporalService.startEvaluationRunWorkflow(evaluationDefinition.id, event, evaluationRuntime)+ await temporalService.startEvaluationRunWorkflow(evaluationDefinition.id, event, evaluationRuntime)+ }evaluationSchedulerEventsProcessed.labels({ status: 'success', type: 'evaluation' }).inc()}diff --git a/nodejs/src/ai-observability/services/evaluation-manager.service.ts b/nodejs/src/ai-observability/services/evaluation-manager.service.tsindex 0a2f49148827..578a73ac90d9 100644--- a/nodejs/src/ai-observability/services/evaluation-manager.service.ts+++ b/nodejs/src/ai-observability/services/evaluation-manager.service.ts@@ -18,6 +18,8 @@ const EVALUATION_FIELDS = ['e.output_type','e.output_config','e.conditions',+ 'e.target',+ 'e.target_config','e.created_at','e.updated_at',]diff --git a/nodejs/src/ai-observability/services/temporal.service.test.ts b/nodejs/src/ai-observability/services/temporal.service.test.tsindex 4106802a9012..830750e10b3a 100644--- a/nodejs/src/ai-observability/services/temporal.service.test.ts+++ b/nodejs/src/ai-observability/services/temporal.service.test.ts@@ -1,9 +1,9 @@-import { Client, Connection } from '@temporalio/client'+import { Client, Connection, WorkflowExecutionAlreadyStartedError } from '@temporalio/client'import { EncryptionCodec } from '~/common/temporal/codec'import { RawKafkaEvent } from '~/types'-import { TemporalService } from './temporal.service'+import { DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS, TemporalService, workflowSafeTraceId } from './temporal.service'import type { EvaluationWorkflowRuntime, TemporalServiceConfig } from './temporal.service'jest.mock('@temporalio/client')@@ -275,4 +275,97 @@ describe('TemporalService', () => {)})})++ describe('trace evaluation workflows', () => {+ it('starts the trace workflow with slim inputs and the passed aggregation window', async () => {+ const mockEvent = createMockEvent()++ await service.startTraceEvaluationRunWorkflow('eval-123', mockEvent, 'trace-789', 'session-1', 60)++ expect(mockClient.workflow.start).toHaveBeenCalledWith('run-trace-evaluation', {+ taskQueue: 'llm-analytics-evals-task-queue',+ workflowId: 'llma-trace-eval-eval-123-trace-789',+ workflowIdConflictPolicy: 'USE_EXISTING',+ workflowIdReusePolicy: 'ALLOW_DUPLICATE_FAILED_ONLY',+ workflowTaskTimeout: '2 minutes',+ args: [+ {+ evaluation_id: 'eval-123',+ team_id: 1,+ trace_id: 'trace-789',+ distinct_id: 'test-user',+ session_id: 'session-1',+ window_seconds: 60,+ },+ ],+ })+ })++ it('produces the same workflow id for every event of the same trace', async () => {+ await service.startTraceEvaluationRunWorkflow(+ 'eval-123',+ createMockEvent({ uuid: 'event-1' }),+ 'trace-789',+ null,+ DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS+ )+ await service.startTraceEvaluationRunWorkflow(+ 'eval-123',+ createMockEvent({ uuid: 'event-2' }),+ 'trace-789',+ null,+ DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS+ )++ 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).not.toContain('event-1')+ })++ it('returns null when a completed run already exists for the trace', async () => {+ ;(mockClient.workflow.start as jest.Mock).mockRejectedValue(+ new WorkflowExecutionAlreadyStartedError('already started', 'wf-id', 'run-trace-evaluation')+ )++ const handle = await service.startTraceEvaluationRunWorkflow(+ 'eval-123',+ createMockEvent(),+ 'trace-789',+ null,+ DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS+ )++ expect(handle).toBeNull()+ })++ it('rethrows non-dedup start failures', async () => {+ ;(mockClient.workflow.start as jest.Mock).mockRejectedValue(new Error('Temporal unavailable'))++ await expect(+ service.startTraceEvaluationRunWorkflow(+ 'eval-123',+ createMockEvent(),+ 'trace-789',+ null,+ DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS+ )+ ).rejects.toThrow('Temporal unavailable')+ })+ })++ describe('workflowSafeTraceId', () => {+ it('keeps short trace ids as-is', () => {+ expect(workflowSafeTraceId('trace-789')).toBe('trace-789')+ })++ it('hashes oversized trace ids deterministically', () => {+ const longTraceId = 'x'.repeat(500)++ const safeId = workflowSafeTraceId(longTraceId)++ expect(safeId).toHaveLength(32)+ expect(safeId).toBe(workflowSafeTraceId(longTraceId))+ expect(safeId).not.toBe(workflowSafeTraceId(`${longTraceId}y`))+ })+ })})diff --git a/nodejs/src/ai-observability/services/temporal.service.ts b/nodejs/src/ai-observability/services/temporal.service.tsindex 044beb546c47..3dc5a11d291d 100644--- a/nodejs/src/ai-observability/services/temporal.service.ts+++ b/nodejs/src/ai-observability/services/temporal.service.ts@@ -1,4 +1,12 @@-import { Client, Connection, DataConverter, TLSConfig, WorkflowHandle } from '@temporalio/client'+import {+ Client,+ Connection,+ DataConverter,+ TLSConfig,+ WorkflowExecutionAlreadyStartedError,+ WorkflowHandle,+} from '@temporalio/client'+import * as crypto from 'crypto'import fs from 'fs/promises'import { Counter } from 'prom-client'@@ -41,12 +49,29 @@ function getEvaluationWorkflowPrefix(evaluationRuntime: EvaluationWorkflowRuntimreturn EVALUATION_WORKFLOW_PREFIXES[evaluationRuntime]}+// Fallback aggregation window when an evaluation's target_config carries no window_seconds.+// Per-eval values come from the eval config; this only applies to legacy/empty configs. Must+// comfortably exceed a single LLM turn (seconds, or a few minutes with heavy tool usage).+export const DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS = 30 * 60+const temporalWorkflowsStarted = new Counter({name: 'evaluation_run_workflows_started',help: 'Number of evaluation run workflows started',labelNames: ['status'],})+/**+ * Trace ids are user-controlled and unbounded; Temporal workflow ids are capped at 1000+ * bytes. Hash anything suspiciously long so the workflow id stays valid while remaining+ * deterministic for dedup.+ */+export function workflowSafeTraceId(traceId: string): string {+ if (traceId.length <= 128) {+ return traceId+ }+ return crypto.createHash('md5').update(traceId).digest('hex')+}+export class TemporalService {private client?: Clientprivate connecting?: Promise<Client>@@ -185,6 +210,67 @@ export class TemporalService {return handle}+ /**+ * Start (or join) the delayed whole-trace evaluation for (evaluation, trace).+ *+ * The workflow id deliberately excludes the event uuid: the first matching generation of a+ * trace creates the workflow, and every later one lands on it as a no-op (USE_EXISTING+ * while pending/running). Once a run completed, ALLOW_DUPLICATE_FAILED_ONLY rejects new+ * starts — a trace is evaluated at most once per evaluation, which also caps the damage+ * from runaway shared trace ids ("0", "fixed_id", ...). Returns null when the trace was+ * already evaluated.+ */+ async startTraceEvaluationRunWorkflow(+ evaluationId: string,+ event: RawKafkaEvent,+ traceId: string,+ sessionId: string | null,+ windowSeconds: number+ ): Promise<WorkflowHandle | null> {+ const client = await this.ensureConnected()++ const workflowId = `llma-trace-eval-${evaluationId}-${workflowSafeTraceId(traceId)}`++ try {+ const handle = await client.workflow.start('run-trace-evaluation', {+ args: [+ {+ evaluation_id: evaluationId,+ team_id: event.team_id,+ trace_id: traceId,+ distinct_id: event.distinct_id,+ session_id: sessionId,+ window_seconds: windowSeconds,+ },+ ],+ taskQueue: EVALUATION_TASK_QUEUE,+ workflowId,+ workflowIdConflictPolicy: 'USE_EXISTING',+ workflowIdReusePolicy: 'ALLOW_DUPLICATE_FAILED_ONLY',+ workflowTaskTimeout: '2 minutes',+ })++ temporalWorkflowsStarted.labels({ status: 'success' }).inc()++ logger.debug('Started trace evaluation run workflow', {+ workflowId,+ evaluationId,+ traceId,+ timestamp: event.timestamp,+ })++ return handle+ } catch (error) {+ // A completed run for this (evaluation, trace) already exists — the expected+ // outcome for every matching event after the trace was evaluated.+ if (error instanceof WorkflowExecutionAlreadyStartedError) {+ temporalWorkflowsStarted.labels({ status: 'already_completed' }).inc()+ return null+ }+ throw error+ }+ }+async startTaggerRunWorkflow(taggerId: string, event: RawKafkaEvent): Promise<WorkflowHandle> {const client = await this.ensureConnected()diff --git a/nodejs/src/ai-observability/types.ts b/nodejs/src/ai-observability/types.tsindex 932f70611187..8ff3b87dcd56 100644--- a/nodejs/src/ai-observability/types.ts+++ b/nodejs/src/ai-observability/types.ts@@ -3,6 +3,7 @@ import { PropertyFilter } from '../types'export type EvaluationStatus = 'active' | 'paused' | 'error'export type EvaluationStatusReason = 'trial_limit_reached' | 'model_not_allowed' | 'provider_key_deleted'+export type EvaluationTarget = 'generation' | 'trace'export interface Evaluation {id: string@@ -17,6 +18,9 @@ export interface Evaluation {output_type: stringoutput_config: Record<string, any>conditions: EvaluationConditionSet[]+ target: EvaluationTarget+ // Target-specific settings keyed off `target`. Trace targets carry the aggregation window.+ target_config: { window_seconds?: number }provider_key_id?: string | nullcreated_at: stringupdated_at: stringdiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 9da721cc2b3d..23238a7fd233 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -488,6 +488,7 @@ SPECTACULAR_SETTINGS = {"PropertyDefinitionTypeEnum": "products.event_definitions.backend.models.property_definition.PropertyType","ExternalDataSourceTypeEnum": "products.warehouse_sources.backend.types.ExternalDataSourceType","ExperimentMetricKindEnum": "products.ai_observability.backend.models.score_definitions.ScoreDefinition.Kind",+ "EvaluationTargetEnum": "products.ai_observability.backend.models.evaluations.EvaluationTarget","IntegrationKindEnum": "posthog.models.integration.Integration.IntegrationKind","TicketStatusEnum": "products.conversations.backend.models.constants.Status","HealthIssueStatusEnum": "posthog.models.health_issue.HealthIssue.Status",diff --git a/posthog/temporal/ai_observability/__init__.py b/posthog/temporal/ai_observability/__init__.pyindex 983c476c3f58..3fb55bd461ae 100644--- a/posthog/temporal/ai_observability/__init__.py+++ b/posthog/temporal/ai_observability/__init__.py@@ -51,6 +51,12 @@ from posthog.temporal.ai_observability.run_tagger import (execute_tagger_activity,fetch_tagger_activity,)+from posthog.temporal.ai_observability.run_trace_evaluation import (+ RunTraceEvaluationWorkflow,+ emit_trace_evaluation_event_activity,+ execute_trace_hog_eval_activity,+ execute_trace_llm_judge_activity,+)from posthog.temporal.ai_observability.shared_activities import (fetch_all_clustering_filters_activity,fetch_all_clustering_jobs_activity,@@ -76,6 +82,7 @@ from products.signals.backend.temporal.emit_eval_signal import emit_eval_signal_EVAL_WORKFLOWS = [RunEvaluationWorkflow,+ RunTraceEvaluationWorkflow,]EVAL_ACTIVITIES = [@@ -88,7 +95,10 @@ EVAL_ACTIVITIES = [execute_llm_judge_activity,execute_hog_eval_activity,execute_sentiment_eval_activity,+ execute_trace_llm_judge_activity,+ execute_trace_hog_eval_activity,emit_evaluation_event_activity,+ emit_trace_evaluation_event_activity,emit_internal_telemetry_activity,emit_eval_signal_activity, # kept for in-flight v1 workflows, then remove]diff --git a/posthog/temporal/ai_observability/evaluation_hog.py b/posthog/temporal/ai_observability/evaluation_hog.pyindex 308e09449dfc..2cd9d23159ed 100644--- a/posthog/temporal/ai_observability/evaluation_hog.py+++ b/posthog/temporal/ai_observability/evaluation_hog.py@@ -20,36 +20,25 @@ from common.hogvm.python.utils import HogVMException, HogVMMemoryExceededExceptilogger = structlog.get_logger(__name__)-def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = False) -> dict[str, Any]:- """Run compiled Hog bytecode against a single event.+def coerce_hog_io_value(value: Any) -> str:+ """Coerce an extracted input/output value into a string for Hog globals.- Used by both the Temporal activity and the test endpoint.- Returns {"verdict": bool | None, "reasoning": str, "error": str | None}.- When allows_na=True, a `return null` is treated as N/A (not an error).- Sets "unexpected": True only when the bytecode raised something other than a- HogVM error — i.e. a bug in our code rather than in the user's Hog source.+ String operations (ilike, length, etc.) should work consistently; users can still+ parse structured data with jsonParse() when needed."""- properties = event_data["properties"]- if isinstance(properties, str):- properties = json.loads(properties)+ if isinstance(value, list | dict):+ return json.dumps(value)+ return "" if value is None or value == "" else str(value)- event_type = event_data["event"]- input_raw, output_raw = extract_event_io(event_type, properties)- input_val = json.dumps(input_raw) if isinstance(input_raw, list | dict) else (input_raw or "")- output_val = json.dumps(output_raw) if isinstance(output_raw, list | dict) else (output_raw or "")-- globals_dict: dict[str, Any] = {- "input": input_val,- "output": output_val,- "properties": properties,- "event": {- "uuid": event_data.get("uuid", ""),- "event": event_type,- "distinct_id": event_data.get("distinct_id", ""),- },- }+def execute_hog_eval_bytecode(bytecode: list, globals_dict: dict[str, Any], allows_na: bool) -> dict[str, Any]:+ """Run compiled Hog eval bytecode against pre-built globals and shape the verdict.+ Shared by the single-event and trace-level Hog activities — only the globals differ.+ Returns {"verdict": bool | None, "reasoning": str, "error": str | None}, plus "applicable"+ when allows_na and a `return null` is treated as N/A, and "unexpected": True when the failure+ was a bug in our code rather than in the user's Hog source.+ """try:response = execute_bytecode(bytecode,@@ -91,6 +80,36 @@ def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = Freturn result+def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = False) -> dict[str, Any]:+ """Run compiled Hog bytecode against a single event.++ Used by both the Temporal activity and the test endpoint.+ Returns {"verdict": bool | None, "reasoning": str, "error": str | None}.+ When allows_na=True, a `return null` is treated as N/A (not an error).+ Sets "unexpected": True only when the bytecode raised something other than a+ HogVM error — i.e. a bug in our code rather than in the user's Hog source.+ """+ properties = event_data["properties"]+ if isinstance(properties, str):+ properties = json.loads(properties)++ event_type = event_data["event"]+ input_raw, output_raw = extract_event_io(event_type, properties)++ globals_dict: dict[str, Any] = {+ "input": coerce_hog_io_value(input_raw),+ "output": coerce_hog_io_value(output_raw),+ "properties": properties,+ "event": {+ "uuid": event_data.get("uuid", ""),+ "event": event_type,+ "distinct_id": event_data.get("distinct_id", ""),+ },+ }++ return execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=allows_na)++@temporalio.activity.defnasync def execute_hog_eval_activity(evaluation: dict[str, Any], event_data: dict[str, Any]) -> EvaluationActivityResult:"""Execute Hog code to evaluate the target event."""diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.pyindex 9f5a32a516e3..0da99ccb7136 100644--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py@@ -214,6 +214,42 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActiif _is_errored_trace(properties):return _build_errored_trace_result(allows_na)+ input_raw, output_raw = extract_event_io(event_type, properties)+ tools_raw = extract_event_tools(properties)++ input_data = extract_text_from_messages(input_raw)+ output_data = extract_text_from_messages(output_raw)+ tools_data = format_tool_definitions(tools_raw)++ system_prompt = build_system_prompt(prompt, allows_na)++ sections = [f"Input: {input_data}"]+ if tools_data:+ sections.append(f"Tools available:\n{tools_data}")+ sections.append(f"Output: {output_data}")+ user_prompt = "\n\n".join(sections)++ return call_llm_judge(+ evaluation=evaluation,+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ allows_na=allows_na,+ )+++def call_llm_judge(+ *,+ evaluation: dict[str, Any],+ system_prompt: str,+ user_prompt: str,+ allows_na: bool,+) -> EvaluationActivityResult:+ """Resolve the judge model/key for `evaluation` and run a single judge completion.++ Shared by the single-event and trace-level judge activities — everything from provider+ resolution through error mapping and result shaping is identical between them; only how the+ user prompt is assembled differs.+ """team_id = evaluation["team_id"]try:resolved = model_spec(evaluation.get("model_configuration")).resolve(team_id)@@ -230,23 +266,9 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActiis_byok = resolved.is_byokkey_id = str(provider_key.id) if provider_key else None- input_raw, output_raw = extract_event_io(event_type, properties)- tools_raw = extract_event_tools(properties)-- input_data = extract_text_from_messages(input_raw)- output_data = extract_text_from_messages(output_raw)- tools_data = format_tool_definitions(tools_raw)-type_config = get_output_type_config(allows_na)- system_prompt = build_system_prompt(prompt, allows_na)response_format = type_config.response_format- sections = [f"Input: {input_data}"]- if tools_data:- sections.append(f"Tools available:\n{tools_data}")- sections.append(f"Output: {output_data}")- user_prompt = "\n\n".join(sections)-config = get_eval_config(provider) if provider_key is None else Noneclient = Client(diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.pyindex d57b4c48410f..1eaf6bd2252e 100644--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py@@ -70,6 +70,8 @@ async def fetch_evaluation_activity(inputs: RunEvaluationInputs) -> dict[str, An"output_config": evaluation.output_config,"team_id": evaluation.team_id,"model_configuration": model_configuration,+ "enabled": evaluation.enabled,+ "deleted": evaluation.deleted,}except Evaluation.DoesNotExist:logger.exception("Evaluation not found", evaluation_id=inputs.evaluation_id)@@ -331,6 +333,60 @@ class EmitEvaluationEventInputs:}+def build_evaluation_event_properties(+ evaluation: dict[str, Any], result: EvaluationActivityResult, start_time: datetime+) -> dict[str, Any]:+ """Assemble the target-independent `$ai_evaluation` properties shared by all emit paths.++ Callers add the target linkage on top ($ai_target_id / $ai_target_type and friends) —+ generation evals point at the source event UUID, trace evals at the trace id.+ """+ allows_na = result.get("allows_na", False)+ evaluation_type = evaluation.get("evaluation_type", "llm_judge")++ properties: dict[str, Any] = {+ "$ai_evaluation_id": evaluation["id"],+ "$ai_evaluation_name": evaluation["name"],+ "$ai_evaluation_type": "online",+ "$ai_evaluation_runtime": evaluation_type,+ "$ai_evaluation_result_type": result["result_type"],+ "$ai_evaluation_start_time": start_time.isoformat(),+ "$ai_evaluation_reasoning": result["reasoning"],+ }++ if result.get("skipped"):+ properties["$ai_evaluation_skipped"] = True+ properties["$ai_evaluation_skip_reason"] = result.get("skip_reason")++ if evaluation_type == "llm_judge" and not result.get("skipped"):+ properties["$ai_model"] = result.get("model", DEFAULT_JUDGE_MODEL)+ properties["$ai_provider"] = result.get("provider", "openai")+ properties["$ai_input_tokens"] = result.get("input_tokens", 0)+ properties["$ai_output_tokens"] = result.get("output_tokens", 0)+ properties["$ai_evaluation_model"] = result.get("model", DEFAULT_JUDGE_MODEL)+ properties["$ai_evaluation_provider"] = result.get("provider", "openai")+ properties["$ai_evaluation_key_type"] = "byok" if result.get("is_byok") else "posthog"+ properties["$ai_evaluation_key_id"] = result.get("key_id")++ if result["result_type"] == "sentiment":+ properties["$ai_sentiment_label"] = result.get("sentiment_label")+ properties["$ai_sentiment_score"] = result.get("sentiment_score")+ properties["$ai_sentiment_scores"] = result.get("sentiment_scores")+ properties["$ai_sentiment_messages"] = result.get("sentiment_messages")+ properties["$ai_sentiment_message_count"] = result.get("sentiment_message_count")+ else:+ properties["$ai_evaluation_allows_na"] = allows_na+ if allows_na:+ applicable = result.get("applicable", True)+ properties["$ai_evaluation_applicable"] = applicable+ if applicable:+ properties["$ai_evaluation_result"] = result["verdict"]+ else:+ properties["$ai_evaluation_result"] = result["verdict"]++ return properties++@temporalio.activity.defnasync def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> None:"""Emit $ai_evaluation event via capture_internal so it routes through the ingestion pipeline for cost calculation."""@@ -346,65 +402,28 @@ async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> Nlogger.exception("Team not found", team_id=event_data["team_id"])raise ValueError(f"Team {event_data['team_id']} not found")- allows_na = result.get("allows_na", False)- evaluation_type = evaluation.get("evaluation_type", "llm_judge")-source_props = (json.loads(event_data["properties"])if isinstance(event_data["properties"], str)else event_data["properties"])- properties: dict[str, Any] = {- "$ai_evaluation_id": evaluation["id"],- "$ai_evaluation_name": evaluation["name"],- "$ai_evaluation_type": "online",- "$ai_evaluation_runtime": evaluation_type,- "$ai_evaluation_result_type": result["result_type"],- "$ai_evaluation_start_time": start_time.isoformat(),- "$ai_evaluation_reasoning": result["reasoning"],- "$ai_target_event_id": event_data["uuid"],- "$ai_target_event_type": event_data["event"],- "$ai_target_id": event_data["uuid"],- "$ai_target_type": "generation_uuid",- "$ai_trace_id": source_props.get("$ai_trace_id"),- "$session_id": source_props.get("$session_id"),- }+ properties = build_evaluation_event_properties(evaluation, result, start_time)+ properties.update(+ {+ "$ai_target_event_id": event_data["uuid"],+ "$ai_target_event_type": event_data["event"],+ "$ai_target_id": event_data["uuid"],+ "$ai_target_type": "generation_uuid",+ "$ai_trace_id": source_props.get("$ai_trace_id"),+ "$session_id": source_props.get("$session_id"),+ }+ )for property_name in SOURCE_AI_PROPERTIES_TO_COPY:if source_props.get(property_name) is not None:properties[property_name] = source_props[property_name]- if result.get("skipped"):- properties["$ai_evaluation_skipped"] = True- properties["$ai_evaluation_skip_reason"] = result.get("skip_reason")-- if evaluation_type == "llm_judge" and not result.get("skipped"):- properties["$ai_model"] = result.get("model", DEFAULT_JUDGE_MODEL)- properties["$ai_provider"] = result.get("provider", "openai")- properties["$ai_input_tokens"] = result.get("input_tokens", 0)- properties["$ai_output_tokens"] = result.get("output_tokens", 0)- properties["$ai_evaluation_model"] = result.get("model", DEFAULT_JUDGE_MODEL)- properties["$ai_evaluation_provider"] = result.get("provider", "openai")- properties["$ai_evaluation_key_type"] = "byok" if result.get("is_byok") else "posthog"- properties["$ai_evaluation_key_id"] = result.get("key_id")-- if result["result_type"] == "sentiment":- properties["$ai_sentiment_label"] = result.get("sentiment_label")- properties["$ai_sentiment_score"] = result.get("sentiment_score")- properties["$ai_sentiment_scores"] = result.get("sentiment_scores")- properties["$ai_sentiment_messages"] = result.get("sentiment_messages")- properties["$ai_sentiment_message_count"] = result.get("sentiment_message_count")- else:- properties["$ai_evaluation_allows_na"] = allows_na- if allows_na:- applicable = result.get("applicable", True)- properties["$ai_evaluation_applicable"] = applicable- if applicable:- properties["$ai_evaluation_result"] = result["verdict"]- else:- properties["$ai_evaluation_result"] = result["verdict"]-event_timestamp = datetime.now(UTC)capture_result = capture_internal(diff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.pyindex 04bc53307c92..eccca272fb0f 100644--- a/posthog/temporal/ai_observability/run_evaluation.py+++ b/posthog/temporal/ai_observability/run_evaluation.py@@ -78,7 +78,10 @@ __all__ = ["extract_event_tools","fetch_evaluation_activity","get_output_type_config",+ "handle_llm_judge_activity_error",+ "handle_terminal_user_error_result","increment_trial_eval_count_activity",+ "increment_trial_usage_and_notify","run_hog_eval","send_evaluation_disabled_email_activity","send_trial_usage_email_activity",@@ -99,6 +102,192 @@ class WorkflowResult(TypedDict, total=False):message: NotRequired[str]+async def handle_llm_judge_activity_error(+ e: temporalio.exceptions.ActivityError, evaluation: dict[str, Any], evaluation_type: str+) -> WorkflowResult | None:+ """Workflow-side handling of terminal LLM judge errors, shared by the single-event and+ trace-level workflows. Must run inside a workflow context.++ For skippable terminal errors, disables the evaluation and sends notification emails where+ appropriate, then returns a skip WorkflowResult the caller should return as-is. For+ provider-key API errors, records the key state and returns None. Returns None for anything+ else — the caller must re-raise.+ """+ if not (isinstance(e.cause, ApplicationError) and e.cause.details):+ return None++ details = application_error_details(e.cause)+ error_type = details.get("error_type")++ terminal_result = terminal_user_error_result_from_application_error(+ e.cause,+ allows_na=(evaluation.get("output_config") or {}).get("allows_na", False),+ )+ if terminal_result is not None:+ return await handle_terminal_user_error_result(+ evaluation=evaluation,+ evaluation_type=evaluation_type,+ result=terminal_result,+ )++ if error_type == "parse_error":+ skip_result: WorkflowResult = {+ "verdict": None,+ "skipped": True,+ "skip_reason": error_type,+ "message": e.cause.message,+ "evaluation_id": evaluation["id"],+ "evaluation_type": evaluation_type,+ }+ return skip_result++ key_id = details.get("key_id")+ if key_id and error_type in ("auth_error", "permission_error", "quota_error", "rate_limit"):+ new_state = LLMProviderKey.State.INVALID if error_type == "auth_error" else LLMProviderKey.State.ERROR+ await temporalio.workflow.execute_activity(+ update_key_state_activity,+ args=[key_id, new_state, e.cause.message],+ schedule_to_close_timeout=timedelta(seconds=10),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+ return None+++async def handle_terminal_user_error_result(+ *,+ evaluation: dict[str, Any],+ evaluation_type: str,+ result: EvaluationActivityResult,+) -> WorkflowResult:+ """Workflow-side handling of a terminal user error surfaced as an activity result, shared by+ the single-event and trace-level workflows. Must run inside a workflow context. Disables the+ evaluation where the error spec calls for it, records provider-key state, sends the+ appropriate notification email, and returns the skip WorkflowResult the caller should return.+ """+ skip_reason = result.get("skip_reason", "terminal_user_error")+ spec = get_evaluation_error_spec(+ str(skip_reason) if skip_reason else None,+ is_byok=bool(result.get("is_byok", False)),+ )+ status_reason = result.get("status_reason")+ disabled_evaluation = False+ if status_reason:+ reasoning = result.get("reasoning")+ status_reason_detail = (+ status_reason_detail_for_terminal_user_error(+ spec,+ reasoning if isinstance(reasoning, str) else None,+ )+ if spec+ else None+ )+ disabled_evaluation = await temporalio.workflow.execute_activity(+ disable_evaluation_activity,+ args=[evaluation["id"], evaluation["team_id"], status_reason, status_reason_detail],+ schedule_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )++ key_id = result.get("key_id")+ provider_key_state = result.get("provider_key_state")+ if key_id and provider_key_state:+ await temporalio.workflow.execute_activity(+ update_key_state_activity,+ args=[str(key_id), provider_key_state, result["reasoning"]],+ schedule_to_close_timeout=timedelta(seconds=10),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )++ if spec and spec.send_trial_usage_email and temporalio.workflow.patched("trial-usage-email"):+ try:+ await temporalio.workflow.execute_activity(+ send_trial_usage_email_activity,+ SendTrialUsageEmailInputs(team_id=evaluation["team_id"], threshold_pct=100),+ activity_id=f"send-trial-usage-email-100pct-{evaluation['team_id']}",+ schedule_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+ except Exception:+ temporalio.workflow.logger.exception(+ "Failed to send trial exhausted email",+ team_id=evaluation["team_id"],+ )++ dedupe_disabled_email = temporalio.workflow.patched("eval-disabled-email-on-disable-transition")+ should_send_disabled_email = (+ spec is not None+ and spec.disables_evaluation+ and bool(status_reason)+ and (disabled_evaluation or not dedupe_disabled_email)+ and not spec.send_trial_usage_email+ and temporalio.workflow.patched("eval-disabled-email")+ )+ if should_send_disabled_email:+ assert spec is not None+ email_status_reason = str(status_reason)+ try:+ await temporalio.workflow.execute_activity(+ send_evaluation_disabled_email_activity,+ SendEvaluationDisabledEmailInputs(+ team_id=evaluation["team_id"],+ evaluation_id=evaluation["id"],+ evaluation_name=evaluation.get("name", "Unknown evaluation"),+ status_reason=email_status_reason,+ human_readable_reason=spec.safe_message,+ disabled_at=temporalio.workflow.now(),+ ),+ activity_id=f"send-eval-disabled-email-{evaluation['id']}-{email_status_reason}",+ schedule_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+ except Exception:+ temporalio.workflow.logger.exception(+ "Failed to send evaluation disabled email",+ evaluation_id=evaluation["id"],+ team_id=evaluation["team_id"],+ )++ workflow_result: WorkflowResult = {+ "verdict": None,+ "skipped": True,+ "skip_reason": skip_reason,+ "message": result["reasoning"],+ "evaluation_id": evaluation["id"],+ "evaluation_type": evaluation_type,+ }+ return workflow_result+++async def increment_trial_usage_and_notify(evaluation: dict[str, Any]) -> None:+ """Increment the team's trial eval counter and send threshold emails. Must run inside a+ workflow context. Shared by the single-event and trace-level workflows; callers gate on+ `is_byok` / `skipped` so only PostHog-key LLM judge runs consume quota.+ """+ threshold_pct = await temporalio.workflow.execute_activity(+ increment_trial_eval_count_activity,+ evaluation["team_id"],+ activity_id=f"increment-trial-{evaluation['id']}",+ schedule_to_close_timeout=timedelta(seconds=10),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )++ if threshold_pct is not None and temporalio.workflow.patched("trial-usage-email"):+ try:+ await temporalio.workflow.execute_activity(+ send_trial_usage_email_activity,+ SendTrialUsageEmailInputs(team_id=evaluation["team_id"], threshold_pct=threshold_pct),+ activity_id=f"send-trial-usage-email-{threshold_pct}pct-{evaluation['team_id']}",+ schedule_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+ except Exception:+ temporalio.workflow.logger.exception(+ "Failed to send trial usage email",+ team_id=evaluation["team_id"],+ threshold_pct=threshold_pct,+ )++@temporalio.workflow.defn(name="run-evaluation")class RunEvaluationWorkflow(PostHogWorkflow):@staticmethod@@ -143,68 +332,13 @@ class RunEvaluationWorkflow(PostHogWorkflow):retry_policy=LLM_JUDGE_RETRY_POLICY,)except temporalio.exceptions.ActivityError as e:- if isinstance(e.cause, ApplicationError) and e.cause.details:- details = application_error_details(e.cause)- error_type = details.get("error_type")- legacy_terminal_result = terminal_user_error_result_from_application_error(- e.cause,- allows_na=(evaluation.get("output_config") or {}).get("allows_na", False),- )- if legacy_terminal_result is not None:- return await self._handle_terminal_user_error_result(- evaluation=evaluation,- evaluation_type=evaluation_type,- result=legacy_terminal_result,- )-- if error_type in ("parse_error",):- skip_result: WorkflowResult = {- "verdict": None,- "skipped": True,- "skip_reason": error_type,- "message": e.cause.message,- "evaluation_id": evaluation["id"],- "evaluation_type": evaluation_type,- }- return skip_result-- key_id = details.get("key_id")- if key_id and error_type in ("auth_error", "permission_error", "quota_error", "rate_limit"):- new_state = (- LLMProviderKey.State.INVALID if error_type == "auth_error" else LLMProviderKey.State.ERROR- )- await temporalio.workflow.execute_activity(- update_key_state_activity,- args=[key_id, new_state, e.cause.message],- schedule_to_close_timeout=timedelta(seconds=10),- retry_policy=RetryPolicy(maximum_attempts=2),- )+ handled = await handle_llm_judge_activity_error(e, evaluation, evaluation_type)+ if handled is not None:+ return handledraiseif not result.get("is_byok") and not result.get("skipped"):- threshold_pct = await temporalio.workflow.execute_activity(- increment_trial_eval_count_activity,- evaluation["team_id"],- activity_id=f"increment-trial-{evaluation['id']}",- schedule_to_close_timeout=timedelta(seconds=10),- retry_policy=RetryPolicy(maximum_attempts=2),- )-- if threshold_pct is not None and temporalio.workflow.patched("trial-usage-email"):- try:- await temporalio.workflow.execute_activity(- send_trial_usage_email_activity,- SendTrialUsageEmailInputs(team_id=evaluation["team_id"], threshold_pct=threshold_pct),- activity_id=f"send-trial-usage-email-{threshold_pct}pct-{evaluation['team_id']}",- schedule_to_close_timeout=timedelta(seconds=30),- retry_policy=RetryPolicy(maximum_attempts=2),- )- except Exception:- temporalio.workflow.logger.exception(- "Failed to send trial usage email",- team_id=evaluation["team_id"],- threshold_pct=threshold_pct,- )+ await increment_trial_usage_and_notify(evaluation)else:raise ApplicationError(f"Unsupported evaluation type: {evaluation_type}",@@ -212,7 +346,7 @@ class RunEvaluationWorkflow(PostHogWorkflow):)if is_terminal_user_error_result(result):- return await self._handle_terminal_user_error_result(+ return await handle_terminal_user_error_result(evaluation=evaluation,evaluation_type=evaluation_type,result=result,@@ -310,103 +444,3 @@ class RunEvaluationWorkflow(PostHogWorkflow):if skip_reason is not None:workflow_result["skip_reason"] = skip_reasonreturn workflow_result-- async def _handle_terminal_user_error_result(- self,- *,- evaluation: dict[str, Any],- evaluation_type: str,- result: EvaluationActivityResult,- ) -> WorkflowResult:- skip_reason = result.get("skip_reason", "terminal_user_error")- spec = get_evaluation_error_spec(- str(skip_reason) if skip_reason else None,- is_byok=bool(result.get("is_byok", False)),- )- status_reason = result.get("status_reason")- disabled_evaluation = False- if status_reason:- reasoning = result.get("reasoning")- status_reason_detail = (- status_reason_detail_for_terminal_user_error(- spec,- reasoning if isinstance(reasoning, str) else None,- )- if spec- else None- )- disabled_evaluation = await temporalio.workflow.execute_activity(- disable_evaluation_activity,- args=[evaluation["id"], evaluation["team_id"], status_reason, status_reason_detail],- schedule_to_close_timeout=timedelta(seconds=30),- retry_policy=RetryPolicy(maximum_attempts=2),- )-- key_id = result.get("key_id")- provider_key_state = result.get("provider_key_state")- if key_id and provider_key_state:- await temporalio.workflow.execute_activity(- update_key_state_activity,- args=[str(key_id), provider_key_state, result["reasoning"]],- schedule_to_close_timeout=timedelta(seconds=10),- retry_policy=RetryPolicy(maximum_attempts=2),- )-- if spec and spec.send_trial_usage_email and temporalio.workflow.patched("trial-usage-email"):- try:- await temporalio.workflow.execute_activity(- send_trial_usage_email_activity,- SendTrialUsageEmailInputs(team_id=evaluation["team_id"], threshold_pct=100),- activity_id=f"send-trial-usage-email-100pct-{evaluation['team_id']}",- schedule_to_close_timeout=timedelta(seconds=30),- retry_policy=RetryPolicy(maximum_attempts=2),- )- except Exception:- temporalio.workflow.logger.exception(- "Failed to send trial exhausted email",- team_id=evaluation["team_id"],- )-- dedupe_disabled_email = temporalio.workflow.patched("eval-disabled-email-on-disable-transition")- should_send_disabled_email = (- spec is not None- and spec.disables_evaluation- and bool(status_reason)- and (disabled_evaluation or not dedupe_disabled_email)- and not spec.send_trial_usage_email- and temporalio.workflow.patched("eval-disabled-email")- )- if should_send_disabled_email:- assert spec is not None- email_status_reason = str(status_reason)- try:- await temporalio.workflow.execute_activity(- send_evaluation_disabled_email_activity,- SendEvaluationDisabledEmailInputs(- team_id=evaluation["team_id"],- evaluation_id=evaluation["id"],- evaluation_name=evaluation.get("name", "Unknown evaluation"),- status_reason=email_status_reason,- human_readable_reason=spec.safe_message,- disabled_at=temporalio.workflow.now(),- ),- activity_id=f"send-eval-disabled-email-{evaluation['id']}-{email_status_reason}",- schedule_to_close_timeout=timedelta(seconds=30),- retry_policy=RetryPolicy(maximum_attempts=2),- )- except Exception:- temporalio.workflow.logger.exception(- "Failed to send evaluation disabled email",- evaluation_id=evaluation["id"],- team_id=evaluation["team_id"],- )-- workflow_result: WorkflowResult = {- "verdict": None,- "skipped": True,- "skip_reason": skip_reason,- "message": result["reasoning"],- "evaluation_id": evaluation["id"],- "evaluation_type": evaluation_type,- }- return workflow_resultdiff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.pynew file mode 100644index 000000000000..c858094f2834--- /dev/null+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py@@ -0,0 +1,584 @@+"""Trace-level evaluation workflow.++The evaluation scheduler starts this workflow when the first $ai_generation matching a+trace-target evaluation arrives. The workflow id (`llma-trace-eval-{evaluation_id}-{trace_id}`)+plus the USE_EXISTING conflict policy make every later matching event of the same trace a+no-op while a run is pending or in flight, and ALLOW_DUPLICATE_FAILED_ONLY prevents+re-evaluating a trace once a run completed. The workflow sleeps for an aggregation window so+the rest of the trace can arrive, then pulls the whole trace from ClickHouse and evaluates it+in one shot.++Temporal payloads are capped at ~2 MiB, so trace content never flows through the workflow:+each execute activity fetches the trace itself and returns only the small verdict dict.+"""++import json+import asyncio+from dataclasses import dataclass+from datetime import UTC, datetime, timedelta+from typing import Any++import structlog+import temporalio+import posthoganalytics+from temporalio.common import RetryPolicy+from temporalio.exceptions import ApplicationError++from posthog.schema import DateRange, LLMTrace, QueryLogTags, TraceQuery++from posthog.hogql import ast+from posthog.hogql.parser import parse_select++from posthog.api.capture import capture_internal+from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events+from posthog.hogql_queries.ai.trace_query_runner import TraceQueryRunner+from posthog.models.team import Team+from posthog.sync import database_sync_to_async+from posthog.temporal.ai_observability.evaluation_errors import (+ is_terminal_user_error_result,+ require_user_error_spec,+ status_reason_detail_for_terminal_user_error,+)+from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io+from posthog.temporal.ai_observability.evaluation_hog import coerce_hog_io_value, execute_hog_eval_bytecode+from posthog.temporal.ai_observability.evaluation_llm_judge import (+ LLM_JUDGE_RETRY_POLICY,+ call_llm_judge,+ get_output_type_config,+)+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult+from posthog.temporal.ai_observability.evaluation_workflow_activities import (+ EmitInternalTelemetryInputs,+ RunEvaluationInputs,+ build_evaluation_event_properties,+ emit_internal_telemetry_activity,+ fetch_evaluation_activity,+)+from posthog.temporal.ai_observability.metrics import increment_emit_event_outcome, increment_errors+from posthog.temporal.ai_observability.run_evaluation import (+ WorkflowResult,+ handle_llm_judge_activity_error,+ handle_terminal_user_error_result,+ increment_trial_usage_and_notify,+)+from posthog.temporal.common.base import PostHogWorkflow++from products.ai_observability.backend.models.evaluation_configs import (+ TRACE_EVAL_DEFAULT_WINDOW_SECONDS,+ TRACE_EVAL_MAX_WINDOW_SECONDS,+)+from products.ai_observability.backend.text_repr.formatters import (+ FormatterOptions,+ format_trace_text_repr,+ llm_trace_to_formatter_format,+)++logger = structlog.get_logger(__name__)++# How far back from the workflow start to look for trace events. The trigger is the first+# *matching* generation, so earlier events of the same trace (spans, prior generations) are+# expected; client-set timestamps far in the past fall outside this window by design.+TRACE_EVENTS_LOOKBACK = timedelta(hours=24)++# Guard against degenerate traces (e.g. a bug attaching everything to trace id "0"): traces+# above this event count are skipped without fetching their payload.+MAX_TRACE_EVAL_EVENTS = 500++# Char budget for the judge transcript. The shared formatter defaults to ~2M chars (sized to+# fill an LLM context window for summarization); a per-trace judge verdict doesn't need that+# much, so we cap lower to bound cost. Over budget, the formatter uniformly samples lines.+JUDGE_TRACE_MAX_CHARS = 150_000++# Heavy payload keys are dropped from per-event `properties` in Hog globals — their content+# is already exposed via the per-event `input`/`output` strings, and duplicating them doubles+# HogVM memory pressure on large traces.+HEAVY_TRACE_PROPERTY_KEYS = (+ "$ai_input",+ "$ai_output",+ "$ai_output_choices",+ "$ai_input_state",+ "$ai_output_state",+ "$ai_tools",+)++# Written against ai_events; query_ai_events rewrites it for the events table when ai_events+# returns nothing. HAVING makes a zero count return no rows, which both triggers the events-table+# fallback and keeps "no events" distinguishable without a second query.+_TRACE_EVENT_COUNT_SQL = """+SELECT count() AS event_count+FROM posthog.ai_events AS ai_events+WHERE event IN ('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')+ AND trace_id = {trace_id}+ AND timestamp >= {date_from}+ AND timestamp <= {date_to}+HAVING event_count > 0+"""++_SKIP_REASONING = {+ "trace_not_found": "No trace events were found within the evaluation window; evaluation skipped.",+ "trace_too_large": (+ f"Trace exceeds {MAX_TRACE_EVAL_EVENTS} events — likely a shared or runaway trace id; evaluation skipped."+ ),+}+++@dataclass+class RunTraceEvaluationInputs:+ evaluation_id: str+ team_id: int+ trace_id: str+ distinct_id: str+ session_id: str | None = None+ window_seconds: int = TRACE_EVAL_DEFAULT_WINDOW_SECONDS++ @property+ def properties_to_log(self) -> dict[str, Any]:+ """Properties for PostHogClientInterceptor error capture."""+ return {+ "evaluation_id": self.evaluation_id,+ "team_id": self.team_id,+ "trace_id": self.trace_id,+ }+++@dataclass+class ExecuteTraceEvaluationInputs:+ evaluation: dict[str, Any]+ team_id: int+ trace_id: str+ window_start: str++ @property+ def properties_to_log(self) -> dict[str, Any]:+ return {+ "team_id": self.team_id,+ "evaluation_id": self.evaluation.get("id"),+ "trace_id": self.trace_id,+ }+++@dataclass+class TraceFetchOutcome:+ trace: LLMTrace | None+ skip_reason: str | None+ event_count: int+++def _count_trace_events(team: Team, trace_id: str, date_from: datetime, date_to: datetime) -> int:+ result = query_ai_events(+ query=parse_select(_TRACE_EVENT_COUNT_SQL),+ placeholders={+ "trace_id": ast.Constant(value=trace_id),+ "date_from": ast.Constant(value=date_from),+ "date_to": ast.Constant(value=date_to),+ },+ team=team,+ query_type="TraceEvaluationEventCount",+ fall_back_to_events=True,+ )+ if not result.results:+ return 0+ return int(result.results[0][0])+++def fetch_trace_for_evaluation(team_id: int, trace_id: str, window_start: datetime) -> TraceFetchOutcome:+ """Fetch the full trace from ClickHouse, with a cheap count preflight so degenerate+ traces are skipped before pulling their payload."""+ team = Team.objects.get(id=team_id)+ date_from = window_start - TRACE_EVENTS_LOOKBACK+ date_to = datetime.now(UTC)++ event_count = _count_trace_events(team, trace_id, date_from, date_to)+ if event_count == 0:+ return TraceFetchOutcome(trace=None, skip_reason="trace_not_found", event_count=0)+ if event_count > MAX_TRACE_EVAL_EVENTS:+ return TraceFetchOutcome(trace=None, skip_reason="trace_too_large", event_count=event_count)++ runner = TraceQueryRunner(+ team=team,+ query=TraceQuery(+ traceId=trace_id,+ dateRange=DateRange(date_from=date_from.isoformat(), date_to=date_to.isoformat()),+ tags=QueryLogTags(productKey="AIObservability"),+ ),+ )+ response = runner.calculate()+ if not response.results:+ return TraceFetchOutcome(trace=None, skip_reason="trace_not_found", event_count=event_count)+ return TraceFetchOutcome(trace=response.results[0], skip_reason=None, event_count=event_count)+++def _build_trace_skip_result(allows_na: bool, skip_reason: str) -> EvaluationActivityResult:+ """Mirror of `_build_errored_trace_result` for trace-level skips — no LLM call is made,+ so model/provider are omitted and downstream cost attribution stays clean."""+ result: EvaluationActivityResult = {+ "result_type": "boolean",+ "verdict": None if allows_na else False,+ "reasoning": _SKIP_REASONING.get(skip_reason, "Evaluation skipped."),+ "allows_na": allows_na,+ "skipped": True,+ "skip_reason": skip_reason,+ }+ if allows_na:+ result["applicable"] = False+ return result+++def build_trace_system_prompt(prompt: str, allows_na: bool) -> str:+ """Trace-level variant of `build_system_prompt` — frames the unit under evaluation as the+ whole trace rather than a single generation."""+ config = get_output_type_config(allows_na)+ return f"""You are an evaluator. Evaluate the following AI trace — the full sequence of LLM calls and operations from one execution — according to this criteria:++{prompt}++{config.instructions}"""+++def format_trace_for_judge(trace: LLMTrace) -> str:+ """Serialize a trace into the canonical text representation for the LLM judge.++ Delegates to the shared `text_repr` formatter — the same plain-text rendering the trace+ view shows users and the trace-summarization workflow feeds its own LLM. Using it here+ means the judge grades exactly what a user sees when they open the trace to debug a+ verdict, and there's one trace serializer to maintain across the product, not a private+ fork. `include_markers=False` drops the frontend expand/collapse markers; the output is+ uniformly sampled down to `JUDGE_TRACE_MAX_CHARS` to bound judge cost and context.+ """+ trace_dict, hierarchy = llm_trace_to_formatter_format(trace)+ options: FormatterOptions = {+ "include_markers": False,+ "collapsed": False,+ "truncated": True,+ "include_line_numbers": True,+ "max_length": JUDGE_TRACE_MAX_CHARS,+ }+ text, _ = format_trace_text_repr(trace_dict, hierarchy, options)+ return text+++def build_trace_hog_globals(trace: LLMTrace, trace_id: str) -> dict[str, Any]:+ """Build Hog globals for a trace-level eval.++ `events` carries every trace event in chronological order with stringified input/output.+ Sources read per-event io off `events`; there is no trace-level `input`/`output` because+ a single synthesized pair isn't meaningful across a whole trace and wouldn't match what+ the trace view shows.+ """+ events_globals: list[dict[str, Any]] = []+ for event in trace.events or []:+ props = event.properties+ input_raw, output_raw = extract_event_io(event.event, props)+ events_globals.append(+ {+ "uuid": event.id,+ "event": event.event,+ "timestamp": event.createdAt,+ "input": coerce_hog_io_value(input_raw),+ "output": coerce_hog_io_value(output_raw),+ "properties": {k: v for k, v in props.items() if k not in HEAVY_TRACE_PROPERTY_KEYS},+ }+ )+ return {+ "events": events_globals,+ "trace": {"id": trace_id, "event_count": len(events_globals)},+ }+++def execute_trace_llm_judge_activity(inputs: ExecuteTraceEvaluationInputs) -> EvaluationActivityResult:+ """Fetch the whole trace and run the LLM judge over its transcript.++ Fetch and judge happen in one activity on purpose: returning the trace through the+ workflow would hit Temporal's ~2 MiB payload limit on large traces.+ """+ evaluation = inputs.evaluation++ if evaluation["evaluation_type"] != "llm_judge":+ raise ApplicationError(+ f"Unsupported evaluation type: {evaluation['evaluation_type']}",+ non_retryable=True,+ )++ prompt = evaluation.get("evaluation_config", {}).get("prompt")+ if not prompt:+ raise ApplicationError("Missing prompt in evaluation_config", non_retryable=True)++ if evaluation["output_type"] != "boolean":+ raise ApplicationError(+ f"Unsupported output type: {evaluation['output_type']}. Supported types: 'boolean'.",+ non_retryable=True,+ )++ allows_na = evaluation.get("output_config", {}).get("allows_na", False)++ outcome = fetch_trace_for_evaluation(inputs.team_id, inputs.trace_id, datetime.fromisoformat(inputs.window_start))+ if outcome.skip_reason or outcome.trace is None:+ return _build_trace_skip_result(allows_na, outcome.skip_reason or "trace_not_found")++ return call_llm_judge(+ evaluation=evaluation,+ system_prompt=build_trace_system_prompt(prompt, allows_na),+ user_prompt=format_trace_for_judge(outcome.trace),+ allows_na=allows_na,+ )+++async def execute_trace_hog_eval_activity(inputs: ExecuteTraceEvaluationInputs) -> EvaluationActivityResult:+ """Fetch the whole trace and run Hog bytecode against trace-level globals."""+ evaluation = inputs.evaluation++ if evaluation["evaluation_type"] != "hog":+ raise ApplicationError(+ f"Unsupported evaluation type: {evaluation['evaluation_type']}",+ non_retryable=True,+ )++ bytecode = evaluation.get("evaluation_config", {}).get("bytecode")+ if not bytecode:+ raise ApplicationError("Missing bytecode in evaluation_config", non_retryable=True)++ allows_na = evaluation.get("output_config", {}).get("allows_na", False)++ def _execute() -> tuple[dict[str, Any] | None, str | None]:+ outcome = fetch_trace_for_evaluation(+ inputs.team_id, inputs.trace_id, datetime.fromisoformat(inputs.window_start)+ )+ if outcome.skip_reason or outcome.trace is None:+ return None, outcome.skip_reason or "trace_not_found"+ globals_dict = build_trace_hog_globals(outcome.trace, inputs.trace_id)+ return execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=allows_na), None++ result, skip_reason = await database_sync_to_async(_execute, thread_sensitive=False)()++ if skip_reason or result is None:+ return _build_trace_skip_result(allows_na, skip_reason or "trace_not_found")++ if result["error"]:+ if result.get("unexpected"):+ # A genuine bug in our evaluation code (not the user's Hog). Raise so the Temporal+ # interceptor reports it to error tracking and we get paged to investigate.+ raise ApplicationError(+ f"Hog evaluation error: {result['error']}",+ non_retryable=True,+ )++ # The user's Hog source itself errored — an expected outcome of running customer-authored+ # code, recorded as a skipped evaluation rather than raised (which would flood error+ # tracking with one event per trace). Marked terminal so the workflow disables the broken+ # eval instead of re-running it against every matching trace (mirrors the generation path).+ spec = require_user_error_spec("hog_error")+ error_detail = status_reason_detail_for_terminal_user_error(spec, result["error"]) or spec.safe_message+ errored_result: EvaluationActivityResult = {+ "result_type": "boolean",+ "verdict": None if allows_na else False,+ "reasoning": error_detail,+ "allows_na": allows_na,+ "skipped": True,+ "skip_reason": "hog_error",+ "terminal_user_error": True,+ "status_reason": spec.status_reason,+ }+ if allows_na:+ errored_result["applicable"] = False+ return errored_result++ activity_result: EvaluationActivityResult = {+ "result_type": "boolean",+ "verdict": result["verdict"],+ "reasoning": result["reasoning"],+ "allows_na": allows_na,+ }+ if allows_na:+ activity_result["applicable"] = result.get("applicable", True)+ return activity_result+++@dataclass+class EmitTraceEvaluationEventInputs:+ evaluation: dict[str, Any]+ team_id: int+ trace_id: str+ distinct_id: str+ session_id: str | None+ result: EvaluationActivityResult+ start_time: datetime++ @property+ def properties_to_log(self) -> dict[str, Any]:+ return {+ "team_id": self.team_id,+ "evaluation_id": self.evaluation.get("id"),+ "trace_id": self.trace_id,+ }+++async def emit_trace_evaluation_event_activity(inputs: EmitTraceEvaluationEventInputs) -> None:+ """Emit the $ai_evaluation event for a trace-level run, targeting the trace id."""++ def _emit():+ try:+ team = Team.objects.get(id=inputs.team_id)+ except Team.DoesNotExist:+ logger.exception("Team not found", team_id=inputs.team_id)+ raise ValueError(f"Team {inputs.team_id} not found")++ # No single source event to inherit from, so SOURCE_AI_PROPERTIES_TO_COPY (span/parent+ # linkage copied in the generation path) intentionally does not apply here.+ properties = build_evaluation_event_properties(inputs.evaluation, inputs.result, inputs.start_time)+ properties.update(+ {+ "$ai_target_id": inputs.trace_id,+ "$ai_target_type": "trace_id",+ # The eval event carries the trace id itself so it shows up inside the trace view.+ "$ai_trace_id": inputs.trace_id,+ "$session_id": inputs.session_id,+ }+ )++ capture_result = capture_internal(+ token=team.api_token,+ event_name="$ai_evaluation",+ event_source="llm_analytics_evaluation",+ distinct_id=inputs.distinct_id,+ timestamp=datetime.now(UTC),+ properties=properties,+ process_person_profile=True,+ )+ capture_result.raise_for_status()++ try:+ await database_sync_to_async(_emit, thread_sensitive=False)()+ increment_emit_event_outcome("success")+ except Exception:+ increment_emit_event_outcome("failed")+ raise++[email protected](name="run-trace-evaluation")+class RunTraceEvaluationWorkflow(PostHogWorkflow):+ @staticmethod+ def parse_inputs(inputs: list[str]) -> RunTraceEvaluationInputs:+ return RunTraceEvaluationInputs(**json.loads(inputs[0]))++ @temporalio.workflow.run+ async def run(self, inputs: RunTraceEvaluationInputs) -> WorkflowResult:+ window_start = temporalio.workflow.now()++ # Wait for the rest of the trace to arrive. Timers are server-side, so sleeping+ # workflows don't hold worker slots.+ window_seconds = min(max(inputs.window_seconds, 0), TRACE_EVAL_MAX_WINDOW_SECONDS)+ if window_seconds:+ await asyncio.sleep(window_seconds)++ eval_start = temporalio.workflow.now()++ evaluation = await temporalio.workflow.execute_activity(+ fetch_evaluation_activity,+ RunEvaluationInputs(evaluation_id=inputs.evaluation_id, event_data={"team_id": inputs.team_id}),+ schedule_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ evaluation_type = evaluation.get("evaluation_type", "llm_judge")++ # The evaluation may have been paused or deleted during the aggregation window —+ # bail out instead of running against config the user just turned off.+ if evaluation["deleted"] or not evaluation["enabled"]:+ disabled_result: WorkflowResult = {+ "verdict": None,+ "skipped": True,+ "skip_reason": "evaluation_deleted" if evaluation["deleted"] else "evaluation_disabled",+ "evaluation_id": inputs.evaluation_id,+ "evaluation_type": evaluation_type,+ }+ return disabled_result++ execute_inputs = ExecuteTraceEvaluationInputs(+ evaluation=evaluation,+ team_id=inputs.team_id,+ trace_id=inputs.trace_id,+ window_start=window_start.isoformat(),+ )++ if evaluation_type == "hog":+ # Unlike single-event hog evals, this activity includes a ClickHouse fetch, so+ # allow one retry for transient query failures (the bytecode is deterministic).+ result = await temporalio.workflow.execute_activity(+ execute_trace_hog_eval_activity,+ execute_inputs,+ schedule_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+ else:+ try:+ result = await temporalio.workflow.execute_activity(+ execute_trace_llm_judge_activity,+ execute_inputs,+ # > single-event judge timeout: the activity also fetches the trace from ClickHouse+ schedule_to_close_timeout=timedelta(minutes=8),+ retry_policy=LLM_JUDGE_RETRY_POLICY,+ )+ except temporalio.exceptions.ActivityError as e:+ handled = await handle_llm_judge_activity_error(e, evaluation, evaluation_type)+ if handled is not None:+ return handled+ raise++ # Trial quota: same gating as the single-event workflow — only PostHog-key LLM+ # judge runs that actually called the API consume quota.+ if not result.get("is_byok") and not result.get("skipped"):+ await increment_trial_usage_and_notify(evaluation)++ if is_terminal_user_error_result(result):+ return await handle_terminal_user_error_result(+ evaluation=evaluation,+ evaluation_type=evaluation_type,+ result=result,+ )++ try:+ await temporalio.workflow.execute_activity(+ emit_trace_evaluation_event_activity,+ EmitTraceEvaluationEventInputs(+ evaluation=evaluation,+ team_id=inputs.team_id,+ trace_id=inputs.trace_id,+ distinct_id=inputs.distinct_id,+ session_id=inputs.session_id,+ result=result,+ start_time=eval_start,+ ),+ schedule_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ except Exception:+ increment_errors("emit_evaluation_event_failed", provider=result.get("provider"))+ raise++ if not result.get("skipped"):+ await temporalio.workflow.execute_activity(+ emit_internal_telemetry_activity,+ EmitInternalTelemetryInputs(+ evaluation=evaluation,+ team_id=inputs.team_id,+ result=result,+ ),+ schedule_to_close_timeout=timedelta(seconds=30),+ )++ workflow_result: WorkflowResult = {+ "verdict": result["verdict"],+ "reasoning": result["reasoning"],+ "evaluation_id": evaluation["id"],+ "evaluation_type": evaluation_type,+ "is_byok": result.get("is_byok", False),+ "skipped": result.get("skipped", False),+ }+ if result.get("skipped"):+ skip_reason = result.get("skip_reason")+ if skip_reason is not None:+ workflow_result["skip_reason"] = skip_reason+ return workflow_resultdiff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.pynew file mode 100644index 000000000000..4ec3aac83c11--- /dev/null+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py@@ -0,0 +1,483 @@+import json+import uuid+from datetime import UTC, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import LLMTrace, LLMTraceEvent++from posthog.cdp.validation import compile_hog+from posthog.models import Organization, Team++from products.ai_observability.backend.models.evaluations import Evaluation++from .evaluation_llm_judge import BooleanEvalResult+from .evaluation_types import EvaluationActivityResult+from .run_trace_evaluation import (+ JUDGE_TRACE_MAX_CHARS,+ MAX_TRACE_EVAL_EVENTS,+ EmitTraceEvaluationEventInputs,+ ExecuteTraceEvaluationInputs,+ RunTraceEvaluationInputs,+ RunTraceEvaluationWorkflow,+ TraceFetchOutcome,+ _build_trace_skip_result,+ build_trace_hog_globals,+ build_trace_system_prompt,+ emit_trace_evaluation_event_activity,+ execute_trace_hog_eval_activity,+ execute_trace_llm_judge_activity,+ fetch_trace_for_evaluation,+ format_trace_for_judge,+)++FROZEN_NOW = datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC)+++def create_trace_event(event: str = "$ai_generation", **properties: Any) -> LLMTraceEvent:+ return LLMTraceEvent(+ id=str(uuid.uuid4()),+ event=event,+ createdAt=FROZEN_NOW.isoformat(),+ properties=properties,+ )+++def create_trace(events: list[LLMTraceEvent], **overrides: Any) -> LLMTrace:+ defaults: dict[str, Any] = {+ "id": "trace-123",+ "createdAt": FROZEN_NOW.isoformat(),+ "distinctId": "test-user",+ "events": events,+ }+ return LLMTrace(**{**defaults, **overrides})+++def setup_data():+ organization = Organization.objects.create(name="Test Org")+ team = Team.objects.create(organization=organization, name="Test Team")+ evaluation = Evaluation.objects.create(+ team=team,+ name="Trace Evaluation",+ evaluation_type="llm_judge",+ evaluation_config={"prompt": "Did the agent resolve the user's request?"},+ output_type="boolean",+ output_config={},+ target="trace",+ enabled=True,+ )+ return {"organization": organization, "team": team, "evaluation": evaluation}+++def evaluation_dict(setup_data: dict, **overrides: Any) -> dict[str, Any]:+ defaults = {+ "id": str(setup_data["evaluation"].id),+ "name": "Trace Evaluation",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Did the agent resolve the user's request?"},+ "output_type": "boolean",+ "output_config": {},+ "team_id": setup_data["team"].id,+ }+ return {**defaults, **overrides}+++# These assert the integration with the shared text_repr formatter — that the judge receives the+# trace's events and content — not the formatter's exact tree art, which text_repr tests itself.+class TestFormatTraceForJudge:+ def test_renders_trace_hierarchy_with_event_content(self):+ trace = create_trace(+ [+ create_trace_event(+ "$ai_span",+ **{"$ai_span_name": "retrieval", "$ai_input_state": "query", "$ai_output_state": "3 docs"},+ ),+ create_trace_event(+ "$ai_generation",+ **{+ "$ai_model": "gpt-4o",+ "$ai_latency": 1.5,+ "$ai_input": [{"role": "user", "content": "What is 2+2?"}],+ "$ai_output_choices": [{"role": "assistant", "content": "4"}],+ },+ ),+ ],+ traceName="math-agent",+ )++ transcript = format_trace_for_judge(trace)++ assert "MATH-AGENT" in transcript+ assert "TRACE HIERARCHY" in transcript+ assert "[GEN]" in transcript+ assert "[SPAN]" in transcript+ assert "gpt-4o" in transcript+ assert "What is 2+2?" in transcript++ def test_includes_tool_catalog(self):+ tools = [{"type": "function", "function": {"name": "search_docs", "description": "Search the docs"}}]+ trace = create_trace(+ [+ create_trace_event("$ai_generation", **{"$ai_input": "hi", "$ai_output": "hello"}),+ create_trace_event("$ai_generation", **{"$ai_tools": tools, "$ai_input": "x", "$ai_output": "y"}),+ ]+ )++ transcript = format_trace_for_judge(trace)++ assert "search_docs" in transcript++ def test_truncates_long_event_io(self):+ trace = create_trace([create_trace_event("$ai_generation", **{"$ai_input": "x" * 50_000})])++ transcript = format_trace_for_judge(trace)++ assert "chars truncated" in transcript++ def test_bounds_output_to_max_chars(self):+ # 200 large generations would blow well past the cap without sampling.+ events = [+ create_trace_event("$ai_generation", **{"$ai_input": f"question {i} " + ("x" * 2_000)}) for i in range(200)+ ]++ transcript = format_trace_for_judge(create_trace(events))++ assert len(transcript) <= JUDGE_TRACE_MAX_CHARS++ def test_marks_errored_events(self):+ trace = create_trace(+ [create_trace_event("$ai_generation", **{"$ai_is_error": True, "$ai_error": "rate limited"})]+ )++ transcript = format_trace_for_judge(trace)++ assert "rate limited" in transcript+++class TestBuildTraceHogGlobals:+ def test_builds_events_with_per_event_input_output(self):+ events = [+ create_trace_event("$ai_span", **{"$ai_input_state": "", "$ai_output_state": ""}),+ create_trace_event("$ai_generation", **{"$ai_input": "first question", "$ai_output": "first answer"}),+ create_trace_event("$ai_generation", **{"$ai_input": "second question", "$ai_output": "final answer"}),+ ]+ trace = create_trace(events)++ globals_dict = build_trace_hog_globals(trace, "trace-123")++ assert "input" not in globals_dict+ assert "output" not in globals_dict+ assert globals_dict["trace"] == {"id": "trace-123", "event_count": 3}+ assert len(globals_dict["events"]) == 3+ assert globals_dict["events"][1]["event"] == "$ai_generation"+ assert globals_dict["events"][1]["input"] == "first question"+ assert globals_dict["events"][2]["output"] == "final answer"++ def test_strips_heavy_keys_from_event_properties(self):+ events = [+ create_trace_event(+ "$ai_generation",+ **{"$ai_input": "question", "$ai_output": "answer", "$ai_model": "gpt-4o", "$ai_tools": ["tool"]},+ )+ ]+ trace = create_trace(events)++ globals_dict = build_trace_hog_globals(trace, "trace-123")++ event_props = globals_dict["events"][0]["properties"]+ assert event_props == {"$ai_model": "gpt-4o"}+++class TestBuildTraceSkipResult:+ def test_skip_result_without_na(self):+ result = _build_trace_skip_result(allows_na=False, skip_reason="trace_too_large")++ assert result["verdict"] is False+ assert result["skipped"] is True+ assert result["skip_reason"] == "trace_too_large"+ assert "applicable" not in result++ def test_skip_result_with_na(self):+ result = _build_trace_skip_result(allows_na=True, skip_reason="trace_not_found")++ assert result["verdict"] is None+ assert result["applicable"] is False+ assert result["skip_reason"] == "trace_not_found"+++class TestFetchTraceForEvaluation:+ @pytest.mark.django_db(transaction=True)+ def test_skips_when_no_events_found(self, setup_data):+ team = setup_data["team"]++ with patch("posthog.temporal.ai_observability.run_trace_evaluation._count_trace_events", return_value=0):+ outcome = fetch_trace_for_evaluation(team.id, "trace-123", FROZEN_NOW)++ assert outcome.skip_reason == "trace_not_found"+ assert outcome.trace is None++ @pytest.mark.django_db(transaction=True)+ def test_skips_oversized_traces_without_fetching(self, setup_data):+ team = setup_data["team"]++ with patch(+ "posthog.temporal.ai_observability.run_trace_evaluation._count_trace_events",+ return_value=MAX_TRACE_EVAL_EVENTS + 1,+ ):+ with patch("posthog.temporal.ai_observability.run_trace_evaluation.TraceQueryRunner") as mock_runner:+ outcome = fetch_trace_for_evaluation(team.id, "trace-123", FROZEN_NOW)++ assert outcome.skip_reason == "trace_too_large"+ assert outcome.event_count == MAX_TRACE_EVAL_EVENTS + 1+ mock_runner.assert_not_called()++ @pytest.mark.django_db(transaction=True)+ def test_returns_trace_when_found(self, setup_data):+ team = setup_data["team"]+ trace = create_trace([create_trace_event("$ai_generation", **{"$ai_input": "q", "$ai_output": "a"})])++ with patch("posthog.temporal.ai_observability.run_trace_evaluation._count_trace_events", return_value=1):+ with patch("posthog.temporal.ai_observability.run_trace_evaluation.TraceQueryRunner") as mock_runner:+ mock_runner.return_value.calculate.return_value = MagicMock(results=[trace])+ outcome = fetch_trace_for_evaluation(team.id, "trace-123", FROZEN_NOW)++ assert outcome.skip_reason is None+ assert outcome.trace is trace+++class TestExecuteTraceLLMJudgeActivity:+ @pytest.mark.django_db(transaction=True)+ def test_judges_full_trace_transcript(self, setup_data):+ trace = create_trace(+ [+ create_trace_event("$ai_generation", **{"$ai_input": "What is 2+2?", "$ai_output": "4"}),+ create_trace_event("$ai_generation", **{"$ai_input": "And times 3?", "$ai_output": "12"}),+ ]+ )++ with patch(+ "posthog.temporal.ai_observability.run_trace_evaluation.fetch_trace_for_evaluation",+ return_value=TraceFetchOutcome(trace=trace, skip_reason=None, event_count=2),+ ):+ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:+ mock_client = MagicMock()+ mock_client_class.return_value = mock_client+ mock_response = MagicMock()+ mock_response.parsed = BooleanEvalResult(verdict=True, reasoning="Resolved both questions")+ mock_response.usage = MagicMock(input_tokens=10, output_tokens=5, total_tokens=15)+ mock_client.complete.return_value = mock_response++ result = execute_trace_llm_judge_activity(+ ExecuteTraceEvaluationInputs(+ evaluation=evaluation_dict(setup_data),+ team_id=setup_data["team"].id,+ trace_id="trace-123",+ window_start=FROZEN_NOW.isoformat(),+ )+ )++ request = mock_client.complete.call_args[0][0]+ content = request.messages[0]["content"]+ assert "AI trace" in request.system+ assert "TRACE HIERARCHY" in content+ assert content.count("[GEN]") == 2+ assert "What is 2+2?" in content+ assert "And times 3?" in content++ assert result["verdict"] is True+ assert result["reasoning"] == "Resolved both questions"++ @pytest.mark.django_db(transaction=True)+ def test_skips_without_llm_call_when_trace_missing(self, setup_data):+ with patch(+ "posthog.temporal.ai_observability.run_trace_evaluation.fetch_trace_for_evaluation",+ return_value=TraceFetchOutcome(trace=None, skip_reason="trace_not_found", event_count=0),+ ):+ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:+ result = execute_trace_llm_judge_activity(+ ExecuteTraceEvaluationInputs(+ evaluation=evaluation_dict(setup_data),+ team_id=setup_data["team"].id,+ trace_id="trace-123",+ window_start=FROZEN_NOW.isoformat(),+ )+ )++ assert result["skipped"] is True+ assert result["skip_reason"] == "trace_not_found"+ mock_client_class.assert_not_called()+++class TestExecuteTraceHogEvalActivity:+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_runs_hog_against_trace_globals(self, setup_data):+ bytecode = compile_hog("return length(events) = 2 and events[2].output = 'final answer'", "destination")+ evaluation = evaluation_dict(+ setup_data,+ evaluation_type="hog",+ evaluation_config={"source": "...", "bytecode": bytecode},+ )+ trace = create_trace(+ [+ create_trace_event("$ai_generation", **{"$ai_input": "q1", "$ai_output": "intermediate"}),+ create_trace_event("$ai_generation", **{"$ai_input": "q2", "$ai_output": "final answer"}),+ ]+ )++ with patch(+ "posthog.temporal.ai_observability.run_trace_evaluation.fetch_trace_for_evaluation",+ return_value=TraceFetchOutcome(trace=trace, skip_reason=None, event_count=2),+ ):+ result = await execute_trace_hog_eval_activity(+ ExecuteTraceEvaluationInputs(+ evaluation=evaluation,+ team_id=setup_data["team"].id,+ trace_id="trace-123",+ window_start=FROZEN_NOW.isoformat(),+ )+ )++ assert result["verdict"] is True++ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_skips_when_trace_too_large(self, setup_data):+ bytecode = compile_hog("return true", "destination")+ evaluation = evaluation_dict(+ setup_data,+ evaluation_type="hog",+ evaluation_config={"source": "return true", "bytecode": bytecode},+ )++ with patch(+ "posthog.temporal.ai_observability.run_trace_evaluation.fetch_trace_for_evaluation",+ return_value=TraceFetchOutcome(trace=None, skip_reason="trace_too_large", event_count=10_000),+ ):+ result = await execute_trace_hog_eval_activity(+ ExecuteTraceEvaluationInputs(+ evaluation=evaluation,+ team_id=setup_data["team"].id,+ trace_id="trace-123",+ window_start=FROZEN_NOW.isoformat(),+ )+ )++ assert result["skipped"] is True+ assert result["skip_reason"] == "trace_too_large"++ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_user_hog_error_is_terminal(self, setup_data):+ # A non-boolean return is a user Hog error; it must be terminal so the workflow disables+ # the broken eval instead of re-running it against every matching trace.+ bytecode = compile_hog("return 42", "destination")+ evaluation = evaluation_dict(+ setup_data,+ evaluation_type="hog",+ evaluation_config={"source": "return 42", "bytecode": bytecode},+ )+ trace = create_trace([create_trace_event("$ai_generation", **{"$ai_input": "q", "$ai_output": "a"})])++ with patch(+ "posthog.temporal.ai_observability.run_trace_evaluation.fetch_trace_for_evaluation",+ return_value=TraceFetchOutcome(trace=trace, skip_reason=None, event_count=1),+ ):+ result = await execute_trace_hog_eval_activity(+ ExecuteTraceEvaluationInputs(+ evaluation=evaluation,+ team_id=setup_data["team"].id,+ trace_id="trace-123",+ window_start=FROZEN_NOW.isoformat(),+ )+ )++ assert result["skipped"] is True+ assert result["skip_reason"] == "hog_error"+ assert result["terminal_user_error"] is True+ assert result["status_reason"]+++class TestEmitTraceEvaluationEventActivity:+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_emits_event_targeting_trace(self, setup_data):+ team = setup_data["team"]+ result: EvaluationActivityResult = {+ "result_type": "boolean",+ "verdict": True,+ "reasoning": "Looks good",+ "allows_na": False,+ "model": "gpt-5-mini",+ "provider": "openai",+ "input_tokens": 42,+ "output_tokens": 18,+ }++ with patch("posthog.temporal.ai_observability.run_trace_evaluation.Team.objects.get", return_value=team):+ with patch("posthog.temporal.ai_observability.run_trace_evaluation.capture_internal") as mock_capture:+ mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())++ await emit_trace_evaluation_event_activity(+ EmitTraceEvaluationEventInputs(+ evaluation=evaluation_dict(setup_data),+ team_id=team.id,+ trace_id="trace-123",+ distinct_id="test-user",+ session_id="session-1",+ result=result,+ start_time=datetime(2024, 1, 1, 12, 0, 0),+ )+ )++ mock_capture.assert_called_once()+ call_kwargs = mock_capture.call_args[1]+ assert call_kwargs["event_name"] == "$ai_evaluation"+ assert call_kwargs["distinct_id"] == "test-user"+ props = call_kwargs["properties"]+ assert props["$ai_target_id"] == "trace-123"+ assert props["$ai_target_type"] == "trace_id"+ assert props["$ai_trace_id"] == "trace-123"+ assert props["$session_id"] == "session-1"+ assert props["$ai_evaluation_result"] is True+ assert props["$ai_model"] == "gpt-5-mini"+ assert "$ai_target_event_id" not in props+ assert "$ai_target_event_type" not in props+++class TestRunTraceEvaluationWorkflowInputs:+ def test_parse_inputs(self):+ payload = {+ "evaluation_id": "eval-123",+ "team_id": 1,+ "trace_id": "trace-456",+ "distinct_id": "user-1",+ "session_id": None,+ "window_seconds": 60,+ }++ parsed = RunTraceEvaluationWorkflow.parse_inputs([json.dumps(payload)])++ assert parsed.evaluation_id == "eval-123"+ assert parsed.trace_id == "trace-456"+ assert parsed.window_seconds == 60++ def test_defaults(self):+ inputs = RunTraceEvaluationInputs(+ evaluation_id="eval-123", team_id=1, trace_id="trace-456", distinct_id="user-1"+ )++ assert inputs.session_id is None+ assert inputs.window_seconds == 30 * 60+++class TestBuildTraceSystemPrompt:+ def test_frames_trace_as_unit_under_evaluation(self):+ prompt = build_trace_system_prompt("Did the agent resolve the request?", allows_na=False)++ assert "AI trace" in prompt+ assert "Did the agent resolve the request?" in prompt+ assert "boolean verdict" in promptdiff --git a/products/ai_observability/backend/api/evaluation_reports.py b/products/ai_observability/backend/api/evaluation_reports.pyindex d8dceb5fe938..1d3a8f799635 100644--- a/products/ai_observability/backend/api/evaluation_reports.py+++ b/products/ai_observability/backend/api/evaluation_reports.py@@ -26,6 +26,7 @@ from products.ai_observability.backend.models.evaluation_configs import (evaluation_supports_reports,)from products.ai_observability.backend.models.evaluation_reports import EvaluationReport, EvaluationReportRun+from products.ai_observability.backend.models.evaluations import EvaluationTargetfrom products.workflows.backend.utils.rrule_utils import validate_rrulelogger = structlog.get_logger(__name__)@@ -138,6 +139,8 @@ class EvaluationReportSerializer(serializers.ModelSerializer):raise serializers.ValidationError("Evaluation does not belong to this team.")if not evaluation_supports_reports(value.output_type):raise serializers.ValidationError("Reports are only supported for boolean evaluations.")+ if value.target == EvaluationTarget.TRACE:+ raise serializers.ValidationError("Reports are not yet supported for trace-level evaluations.")return valuedef validate_rrule(self, value: str) -> str:@@ -433,6 +436,11 @@ class EvaluationReportViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewse{"error": "Reports are only supported for boolean evaluations."},status=status.HTTP_400_BAD_REQUEST,)+ if report.evaluation.target == EvaluationTarget.TRACE:+ return Response(+ {"error": "Reports are not yet supported for trace-level evaluations."},+ status=status.HTTP_400_BAD_REQUEST,+ )try:from posthog.temporal.ai_observability.eval_reports.constants import GENERATE_EVAL_REPORT_WORKFLOW_NAMEdiff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.pyindex 0ec69c60f921..2208dd3cfa79 100644--- a/products/ai_observability/backend/api/evaluations.py+++ b/products/ai_observability/backend/api/evaluations.py@@ -29,15 +29,19 @@ from ..feature_flags import is_sentiment_evaluations_enabledfrom ..hog import compile_ai_observability_hogfrom ..models.evaluation_config import EvaluationConfigfrom ..models.evaluation_configs import (+ TRACE_EVAL_DEFAULT_WINDOW_SECONDS,+ TRACE_EVAL_MAX_WINDOW_SECONDS,+ TRACE_EVAL_MIN_WINDOW_SECONDS,EvaluationType,OutputType,evaluation_supports_reports,evaluation_uses_model_configuration,get_evaluation_config_content_key,validate_evaluation_configs,+ validate_target_config,)from ..models.evaluation_reports import EvaluationReport-from ..models.evaluations import Evaluation, EvaluationStatusReason+from ..models.evaluations import Evaluation, EvaluationStatusReason, EvaluationTargetfrom ..models.model_configuration import LLMModelConfigurationfrom ..models.provider_keys import LLMProvider, LLMProviderKeyfrom .metrics import llma_track_latency@@ -120,6 +124,29 @@ class _OutputConfigField(serializers.JSONField):pass+@extend_schema_field(+ {+ "type": "object",+ "properties": {+ "window_seconds": {+ "type": "integer",+ "description": (+ "For 'trace' target: seconds to wait after the first matching generation before "+ "evaluating the whole trace. Captured when the run is scheduled — editing it does not "+ "change trace runs already in flight."+ ),+ "minimum": TRACE_EVAL_MIN_WINDOW_SECONDS,+ "maximum": TRACE_EVAL_MAX_WINDOW_SECONDS,+ "default": TRACE_EVAL_DEFAULT_WINDOW_SECONDS,+ }+ },+ "additionalProperties": False,+ }+)+class _TargetConfigField(serializers.JSONField):+ pass++class ModelConfigurationSerializer(serializers.Serializer):"""Nested serializer for model configuration."""@@ -185,6 +212,10 @@ class EvaluationSerializer(serializers.ModelSerializer):required=False,help_text="Output config. For 'boolean' output_type: {allows_na} to permit N/A results.",)+ target_config = _TargetConfigField(+ required=False,+ help_text="Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.",+ )conditions = EvaluationConditionSerializer(many=True,required=False,@@ -210,6 +241,8 @@ class EvaluationSerializer(serializers.ModelSerializer):"output_type","output_config","conditions",+ "target",+ "target_config","model_configuration","created_at","updated_at",@@ -242,6 +275,15 @@ class EvaluationSerializer(serializers.ModelSerializer):"Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.")},+ "target": {+ "help_text": (+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event "+ "individually. 'trace' evaluates the whole trace once: the first matching generation schedules "+ "a run that waits for the trace to settle, then evaluates all of its events together. "+ "Condition filters still match individual generations — a trace is evaluated when any of its "+ "generations matches, and sampling applies per trace."+ )+ },"deleted": {"help_text": "Set to true to soft-delete the evaluation."},}@@ -286,6 +328,29 @@ class EvaluationSerializer(serializers.ModelSerializer):except ValueError as e:raise serializers.ValidationError({"config": str(e)})+ # Sentiment is addressed per-message within one generation event ($ai_target_event_id ++ # message index). A trace target emits a single evaluation event for the whole trace, where+ # the message index is ambiguous and that per-generation linkage is absent. Trace-level+ # sentiment is already produced by aggregating generation-target sentiment evals at read time.+ effective_target = data.get("target") or getattr(self.instance, "target", None) or EvaluationTarget.GENERATION+ if evaluation_type == EvaluationType.SENTIMENT.value and effective_target == EvaluationTarget.TRACE.value:+ raise serializers.ValidationError(+ {"target": "Sentiment evaluations can't target a whole trace. Use the 'generation' target."}+ )++ # Validate target_config against the effective target (request value, else the stored one).+ # Surfaces a clean field error for an out-of-range window; the model's save() re-runs this+ # so untouched requests still get normalized.+ if "target" in data or "target_config" in data:+ target = data.get("target") or getattr(self.instance, "target", None) or "generation"+ config = data.get("target_config")+ if config is None:+ config = getattr(self.instance, "target_config", {})+ try:+ data["target_config"] = validate_target_config(target, config or {})+ except ValueError as e:+ raise serializers.ValidationError({"target_config": str(e)})+# Guard re-enable transitions: if the eval is currently disabled and the caller is flipping# `enabled=True`, make sure whatever caused the disabled state has actually been resolved.# Without this check, a caller (UI, API, MCP, agent) can flip enabled=True, see a 200, and@@ -615,7 +680,7 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbiwith transaction.atomic():instance = serializer.save()- if evaluation_supports_reports(instance.output_type):+ if evaluation_supports_reports(instance.output_type) and instance.target == EvaluationTarget.GENERATION:# Auto-create a default report config so reports are generated from the start.# Defaults to count-triggered (frequency=every_n), so rrule/starts_at stay empty# and users add email/Slack delivery targets later if they want notifications.diff --git a/products/ai_observability/backend/api/test/test_evaluation_reports.py b/products/ai_observability/backend/api/test/test_evaluation_reports.pyindex af488804d9d0..593a38581f3f 100644--- a/products/ai_observability/backend/api/test/test_evaluation_reports.py+++ b/products/ai_observability/backend/api/test/test_evaluation_reports.py@@ -13,7 +13,7 @@ from posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom products.ai_observability.backend.models.evaluation_reports import EvaluationReport, EvaluationReportRun-from products.ai_observability.backend.models.evaluations import Evaluation+from products.ai_observability.backend.models.evaluations import Evaluation, EvaluationTargetclass TestEvaluationReportApi(APIBaseTest):@@ -68,6 +68,21 @@ class TestEvaluationReportApi(APIBaseTest):conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],)+ def _create_trace_evaluation(self) -> Evaluation:+ return Evaluation.objects.create(+ team=self.team,+ name="Trace Eval",+ evaluation_type="llm_judge",+ evaluation_config={"prompt": "test"},+ output_type="boolean",+ output_config={},+ target=EvaluationTarget.TRACE,+ target_config={"window_seconds": 60},+ enabled=True,+ created_by=self.user,+ conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],+ )+def test_unauthenticated_user_cannot_access(self):self.client.logout()response = self.client.get(self.base_url)@@ -159,6 +174,38 @@ class TestEvaluationReportApi(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json().get("attr"), "evaluation")+ def test_create_rejects_trace_target_evaluation(self):+ trace_evaluation = self._create_trace_evaluation()+ response = self.client.post(+ self.base_url,+ {+ "evaluation": str(trace_evaluation.id),+ "frequency": "every_n",+ "trigger_threshold": 100,+ "delivery_targets": [],+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json().get("attr"), "evaluation")++ def test_deliverable_excludes_trace_target_reports(self):+ # A report directly attached to a trace eval (e.g. created before the eval switched targets,+ # bypassing the serializer) must not enter the delivery pipeline.+ gen_report = self._create_report()+ trace_report = self._create_report(evaluation=self._create_trace_evaluation())++ deliverable_ids = set(EvaluationReport.objects.deliverable().values_list("id", flat=True))++ self.assertIn(gen_report.id, deliverable_ids)+ self.assertNotIn(trace_report.id, deliverable_ids)++ def test_generate_rejects_trace_target_evaluation(self):+ report = self._create_report(evaluation=self._create_trace_evaluation())+ response = self.client.post(f"{self.base_url}{report.id}/generate/")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+def test_list_excludes_sentiment_reports(self):sentiment_evaluation = self._create_sentiment_evaluation()EvaluationReport.objects.create(diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.pyindex 752bcdd22660..5d8d9b11eaf4 100644--- a/products/ai_observability/backend/api/test/test_evaluations.py+++ b/products/ai_observability/backend/api/test/test_evaluations.py@@ -87,6 +87,132 @@ class TestEvaluationConfigsApi(APIBaseTest):self.assertFalse(report.deleted)self.assertEqual(report.delivery_targets, [])+ def test_target_defaults_to_generation(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/",+ {+ "name": "Default target",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Test prompt"},+ "output_type": "boolean",+ "output_config": {},+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],+ },+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["target"], "generation")++ def test_can_create_trace_target_evaluation(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/",+ {+ "name": "Trace target",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Test prompt"},+ "output_type": "boolean",+ "output_config": {},+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],+ "target": "trace",+ },+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["target"], "trace")+ evaluation = Evaluation.objects.get(name="Trace target")+ self.assertEqual(evaluation.target, "trace")+ self.assertEqual(evaluation.target_config, {"window_seconds": 30 * 60})+ # Reports run a generation-oriented agent — a trace eval must not get an auto-created report.+ self.assertEqual(EvaluationReport.objects.filter(evaluation=evaluation).count(), 0)++ def test_trace_target_accepts_custom_window(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/",+ {+ "name": "Trace custom window",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Test prompt"},+ "output_type": "boolean",+ "output_config": {},+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],+ "target": "trace",+ "target_config": {"window_seconds": 120},+ },+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["target_config"], {"window_seconds": 120})++ def test_rejects_window_below_minimum(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/",+ {+ "name": "Trace tiny window",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Test prompt"},+ "output_type": "boolean",+ "output_config": {},+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],+ "target": "trace",+ "target_config": {"window_seconds": 5},+ },+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "target_config")++ def test_generation_target_strips_window_config(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/",+ {+ "name": "Generation with stray config",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Test prompt"},+ "output_type": "boolean",+ "output_config": {},+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],+ "target": "generation",+ "target_config": {"window_seconds": 120},+ },+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["target_config"], {})++ def test_rejects_unknown_window_config_key(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/",+ {+ "name": "Trace unknown key",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Test prompt"},+ "output_type": "boolean",+ "output_config": {},+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],+ "target": "trace",+ "target_config": {"window_seconds": 120, "unexpected": True},+ },+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "target_config")++ def test_rejects_invalid_target(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/",+ {+ "name": "Bad target",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Test prompt"},+ "output_type": "boolean",+ "output_config": {},+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],+ "target": "session",+ },+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+def test_evaluation_rollback_when_auto_report_fails(self):"""perform_create wraps the Evaluation save and the EvaluationReport auto-create in@@ -136,6 +262,25 @@ class TestEvaluationConfigsApi(APIBaseTest):self.assertEqual(evaluation.output_config, {})self.assertEqual(EvaluationReport.objects.filter(evaluation=evaluation).count(), 0)+ def test_rejects_sentiment_evaluation_with_trace_target(self):+ with patch("products.ai_observability.backend.feature_flags.feature_enabled_or_false", return_value=True):+ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/",+ {+ "name": "Sentiment over a trace",+ "evaluation_type": "sentiment",+ "evaluation_config": {},+ "output_type": "sentiment",+ "output_config": {},+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],+ "target": "trace",+ },+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "target")+ self.assertEqual(Evaluation.objects.count(), 0)+def test_create_sentiment_evaluation_requires_feature_flag(self):with patch("products.ai_observability.backend.feature_flags.feature_enabled_or_false", return_value=False):response = self.client.post(diff --git a/products/ai_observability/backend/models/evaluation_reports.py b/products/ai_observability/backend/models/evaluation_reports.pyindex 659e60389cf3..09f58ca90d30 100644--- a/products/ai_observability/backend/models/evaluation_reports.py+++ b/products/ai_observability/backend/models/evaluation_reports.py@@ -9,10 +9,19 @@ from posthog.models.utils import UUIDTModelfrom products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule+from .evaluations import EvaluationTarget+class EvaluationReportQuerySet(models.QuerySet):def deliverable(self) -> "EvaluationReportQuerySet":- return self.filter(enabled=True, deleted=False, evaluation__deleted=False)+ # Reports run a generation-oriented agent, so trace-target evals never deliver — this+ # also covers evals switched from generation to trace after a report was created.+ return self.filter(+ enabled=True,+ deleted=False,+ evaluation__deleted=False,+ evaluation__target=EvaluationTarget.GENERATION,+ )class EvaluationReport(UUIDTModel):diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsxindex dbd3e31537c3..443c42e5bdc2 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx@@ -19,6 +19,7 @@ import {} from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'+import { DurationPicker } from 'lib/components/DurationPicker/DurationPicker'import { NotFound } from 'lib/components/NotFound'import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast'@@ -47,9 +48,9 @@ import {evaluationTypeSupportsSignalEmission,evaluationTypeUsesModelConfiguration,} from './evaluationCapabilities'-import { LLMEvaluationLogicProps, llmEvaluationLogic } from './llmEvaluationLogic'+import { DEFAULT_TRACE_WINDOW_SECONDS, LLMEvaluationLogicProps, llmEvaluationLogic } from './llmEvaluationLogic'import { statusReasonLabel, statusReasonRecoveryLabel } from './statusDisplay'-import { EvaluationType } from './types'+import { EvaluationTarget, EvaluationType } from './types'export function AIObservabilityEvaluation(): JSX.Element {const {@@ -78,6 +79,8 @@ export function AIObservabilityEvaluation(): JSX.Element {saveEvaluation,resetEvaluation,setEvaluationType,+ setEvaluationTarget,+ setTraceWindowSeconds,setSignalEmission,setActiveTab,} = useActions(llmEvaluationLogic)@@ -461,6 +464,54 @@ export function AIObservabilityEvaluation(): JSX.Element {)}</p>+ {featureFlags[FEATURE_FLAGS.AI_OBSERVABILITY_EVALUATIONS_TRACE_TARGET] &&+ !isSentiment && (+ <>+ <Field name="target" label="Evaluate">+ <LemonSelect<EvaluationTarget>+ value={evaluation.target ?? 'generation'}+ onChange={setEvaluationTarget}+ options={[+ {+ value: 'generation',+ label: 'Each generation',+ },+ {+ value: 'trace',+ label: 'Whole trace',+ },+ ]}+ fullWidth+ />+ </Field>+ <p className="text-muted text-sm -mt-2">+ {evaluation.target === 'trace'+ ? 'Runs once per trace on all of its events together, after a delay that lets the trace complete.'+ : 'Runs on each matching generation event individually, right after it is ingested.'}+ </p>+ {evaluation.target === 'trace' && (+ <Field name="trace_window" label="Wait before evaluating">+ <div className="space-y-1">+ <DurationPicker+ value={+ evaluation.target_config.window_seconds ??+ DEFAULT_TRACE_WINDOW_SECONDS+ }+ onChange={setTraceWindowSeconds}+ />+ <p className="text-muted text-xs">+ How long to wait after the first matching+ generation before pulling the whole trace+ (10s–2h). Captured when the run is scheduled —+ changing it won't affect trace runs already in+ flight.+ </p>+ </div>+ </Field>+ )}+ </>+ )}+<Field name="description" label="Description (optional)"><LemonTextAreavalue={evaluation.description || ''}diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsxindex 5aa26bfe6274..f3dabdcd36ce 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx@@ -55,27 +55,41 @@ export function EvaluationRunsTable(): JSX.Element {sorter: (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),},{- title: 'Generation ID',- key: 'generation_id',+ title: 'Target',+ key: 'target',render: (_, run) => {- if (!run.generation_id) {- return <span className="font-mono text-sm text-muted">—</span>+ // Generation-target runs link to the specific event in the trace; trace-target+ // runs (no generation id) link to the whole trace.+ if (run.generation_id) {+ return (+ <div className="font-mono text-sm">+ <Link+ to={+ combineUrl(urls.aiObservabilityTrace(run.trace_id), {+ ...traceSearchParams,+ event: run.generation_id,+ }).url+ }+ className="text-primary"+ >+ {run.generation_id.slice(0, 12)}...+ </Link>+ </div>+ )}- return (- <div className="font-mono text-sm">- <Link- to={- combineUrl(urls.aiObservabilityTrace(run.trace_id), {- ...traceSearchParams,- event: run.generation_id,- }).url- }- className="text-primary"- >- {run.generation_id.slice(0, 12)}...- </Link>- </div>- )+ if (run.trace_id) {+ return (+ <div className="font-mono text-sm">+ <Link+ to={combineUrl(urls.aiObservabilityTrace(run.trace_id), traceSearchParams).url}+ className="text-primary"+ >+ trace {run.trace_id.slice(0, 12)}...+ </Link>+ </div>+ )+ }+ return <span className="font-mono text-sm text-muted">—</span>},},{diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationTriggers.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationTriggers.tsxindex 5eb20e9f0287..15c22d488993 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationTriggers.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationTriggers.tsx@@ -54,11 +54,20 @@ export function EvaluationTriggers(): JSX.Element {setTriggerConditions(updatedConditions)}+ const isTraceTarget = evaluation.target === 'trace'+return (<div className="space-y-6"><div className="text-sm text-muted">Each condition set below defines when this evaluation should trigger. If multiple condition sets exist,the evaluation will trigger if ANY of them match (OR logic).+ {isTraceTarget && (+ <>+ {' '}+ Conditions match individual generations — the whole trace is evaluated once any of its+ generations matches, and sampling applies per trace.+ </>+ )}</div>{evaluation.conditions.map((condition, index) => {@@ -132,7 +141,8 @@ export function EvaluationTriggers(): JSX.Element {</div>) : (<div className="text-xs text-muted">- This evaluation will run on {percentageValue.toFixed(2)}% of matching generations+ This evaluation will run on {percentageValue.toFixed(2)}% of matching{' '}+ {isTraceTarget ? 'traces' : 'generations'}</div>)}</div>diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.tsindex e424a663806f..a3212b521b1c 100644--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts@@ -1,6 +1,6 @@import { FEATURE_FLAGS } from 'lib/constants'-import { evaluationTypeCanBeCreated } from './evaluationCapabilities'+import { evaluationSupportsReports, evaluationTypeCanBeCreated } from './evaluationCapabilities'describe('evaluationCapabilities', () => {it('gates sentiment creation on the sentiment evaluations feature flag', () => {@@ -13,4 +13,10 @@ describe('evaluationCapabilities', () => {})).toBe(true)})++ it('supports reports only for boolean generation-target evaluations', () => {+ expect(evaluationSupportsReports({ output_type: 'boolean', target: 'generation' })).toBe(true)+ expect(evaluationSupportsReports({ output_type: 'boolean', target: 'trace' })).toBe(false)+ expect(evaluationSupportsReports({ output_type: 'sentiment', target: 'generation' })).toBe(false)+ })})diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.tsindex bc72eca2cb47..f10573cb2dd4 100644--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts@@ -8,9 +8,11 @@ export function isBooleanEvaluationOutput(outputType: EvaluationOutputType | nul}export function evaluationSupportsReports(- evaluation: Pick<EvaluationConfig, 'output_type'> | null | undefined+ evaluation: Pick<EvaluationConfig, 'output_type' | 'target'> | null | undefined): boolean {- return isBooleanEvaluationOutput(evaluation?.output_type)+ // Trace-level evals aren't supported by the report agent yet — the backend rejects+ // report creation for them, so hide the report UI rather than surface that error.+ return isBooleanEvaluationOutput(evaluation?.output_type) && evaluation?.target !== 'trace'}export function evaluationTypeUsesModelConfiguration(evaluationType: EvaluationType | null | undefined): boolean {diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.tsindex 7a1787ebfdf7..e05c4b36824c 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts@@ -5,7 +5,7 @@ import { initKeaTests } from '~/test/init'import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import { EVALUATION_SUMMARY_MAX_RUNS } from './constants'-import { DEFAULT_HOG_SOURCE, llmEvaluationLogic } from './llmEvaluationLogic'+import { DEFAULT_HOG_SOURCE, DEFAULT_TRACE_HOG_SOURCE, llmEvaluationLogic } from './llmEvaluationLogic'import { EvaluationConfig, EvaluationRun } from './types'const mockProviderKeys: LLMProviderKey[] = [@@ -76,6 +76,8 @@ const mockEvaluation: EvaluationConfig = {output_type: 'boolean',output_config: { allows_na: false },conditions: [{ id: 'cond-1', rollout_percentage: 50, properties: [] }],+ target: 'generation',+ target_config: {},model_configuration: {provider: 'openai',model: 'gpt-5-mini',@@ -316,6 +318,47 @@ describe('llmEvaluationLogic', () => {await expectLogic(logic).toMatchValues({ hasUnsavedChanges: false })})++ it('seeds the trace Hog default when switching to hog with a trace target', async () => {+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])++ logic.actions.setEvaluationTarget('trace')+ logic.actions.setEvaluationType('hog')++ await expectLogic(logic).toMatchValues({+ evaluation: expect.objectContaining({+ evaluation_config: { source: DEFAULT_TRACE_HOG_SOURCE },+ }),+ })+ })++ it('swaps the untouched Hog default when the target changes', async () => {+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])++ logic.actions.setEvaluationType('hog')+ await expectLogic(logic).toMatchValues({+ evaluation: expect.objectContaining({ evaluation_config: { source: DEFAULT_HOG_SOURCE } }),+ })++ logic.actions.setEvaluationTarget('trace')+ await expectLogic(logic).toMatchValues({+ evaluation: expect.objectContaining({ evaluation_config: { source: DEFAULT_TRACE_HOG_SOURCE } }),+ })+ })++ it('does not clobber an edited Hog source when the target changes', async () => {+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])++ logic.actions.setEvaluationType('hog')+ logic.actions.setHogSource('return length(events) > 5')+ logic.actions.setEvaluationTarget('trace')++ await expectLogic(logic).toMatchValues({+ evaluation: expect.objectContaining({+ evaluation_config: expect.objectContaining({ source: 'return length(events) > 5' }),+ }),+ })+ })})describe('selectors', () => {@@ -851,6 +894,21 @@ describe('llmEvaluationLogic', () => {})})+ it('switching to sentiment resets a trace target back to generation', async () => {+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])++ logic.actions.setEvaluationTarget('trace')+ logic.actions.setEvaluationType('sentiment')++ await expectLogic(logic).toMatchValues({+ evaluation: expect.objectContaining({+ evaluation_type: 'sentiment',+ target: 'generation',+ target_config: {},+ }),+ })+ })+it('initializes new evaluations as sentiment when requested', async () => {logic.unmount()logic = llmEvaluationLogic({ evaluationId: 'new', evaluationType: 'sentiment' })diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.tsindex 9f29a58756a2..e3d8c6fd935c 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts@@ -35,6 +35,7 @@ import type {EvaluationRun,EvaluationSummary,EvaluationSummaryFilter,+ EvaluationTarget,EvaluationType,HogEvaluation,LLMJudgeEvaluation,@@ -43,6 +44,10 @@ import type {SentimentEvaluation,} from './types'+// Mirrors TRACE_EVAL_DEFAULT_WINDOW_SECONDS on the backend — the value pre-filled when an+// evaluation is switched to the trace target. The backend re-defaults and clamps regardless.+export const DEFAULT_TRACE_WINDOW_SECONDS = 30 * 60+export const DEFAULT_HOG_SOURCE = `// Check that the output is not emptylet result := length(output) > 0if (not result) {@@ -50,6 +55,15 @@ if (not result) {}return result`+// Trace Hog globals expose `events` and `trace`, not a top-level `output`, so the generation+// default can't run against them — seed a trace-shaped check instead.+export const DEFAULT_TRACE_HOG_SOURCE = `// Check that the trace produced at least one event+let result := length(events) > 0+if (not result) {+ print('Trace has no events')+}+return result`+const DEFAULT_SENTIMENT_SOURCE = 'user_messages' as constconst DEFAULT_SENTIMENT_RUNS_FILTER = 'negative' as constconst DEFAULT_CONDITION_ROLLOUT_PERCENTAGE = 100@@ -68,7 +82,7 @@ function toHogEvaluation(evaluation: EvaluationConfig): HogEvaluation {return {...evaluation,evaluation_type: 'hog',- evaluation_config: { source: DEFAULT_HOG_SOURCE },+ evaluation_config: { source: evaluation.target === 'trace' ? DEFAULT_TRACE_HOG_SOURCE : DEFAULT_HOG_SOURCE },output_type: 'boolean',model_configuration: null,output_config: { ...evaluation.output_config, allows_na: false },@@ -83,6 +97,9 @@ function toSentimentEvaluation(evaluation: EvaluationConfig): SentimentEvaluatiooutput_type: 'sentiment',output_config: {},model_configuration: null,+ // Sentiment is per-message within a single generation; a trace target is unsupported.+ target: 'generation',+ target_config: {},}}@@ -152,6 +169,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([setTriggerConditions: (conditions: EvaluationConditionSet[]) => ({ conditions }),setModelConfiguration: (modelConfiguration: ModelConfiguration | null) => ({ modelConfiguration }),setEvaluationType: (evaluationType: EvaluationType) => ({ evaluationType }),+ setEvaluationTarget: (target: EvaluationTarget) => ({ target }),+ setTraceWindowSeconds: (windowSeconds: number) => ({ windowSeconds }),setHogSource: (source: string) => ({ source }),// Signal emission@@ -326,6 +345,40 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([}return toLLMJudgeEvaluation(state)},+ setEvaluationTarget: (state, { target }) => {+ if (!state) {+ return null+ }+ // Seed the window when switching to trace so the field shows a sane default;+ // clear the bag when switching back so we don't persist a stale window.+ const target_config = target === 'trace' ? { window_seconds: DEFAULT_TRACE_WINDOW_SECONDS } : {}+ // Swap the default Hog source to match the new target, but only while it's still the+ // untouched default for the other target — never clobber a source the user edited.+ if (state.evaluation_type === 'hog') {+ const source = state.evaluation_config.source+ if (target === 'trace' && source === DEFAULT_HOG_SOURCE) {+ return {+ ...state,+ target,+ target_config,+ evaluation_config: { ...state.evaluation_config, source: DEFAULT_TRACE_HOG_SOURCE },+ }+ }+ if (target !== 'trace' && source === DEFAULT_TRACE_HOG_SOURCE) {+ return {+ ...state,+ target,+ target_config,+ evaluation_config: { ...state.evaluation_config, source: DEFAULT_HOG_SOURCE },+ }+ }+ }+ return { ...state, target, target_config }+ },+ setTraceWindowSeconds: (state, { windowSeconds }) =>+ state+ ? { ...state, target_config: { ...state.target_config, window_seconds: windowSeconds } }+ : null,setHogSource: (state, { source }) =>state && state.evaluation_type === 'hog'? { ...state, evaluation_config: { ...state.evaluation_config, source } }@@ -396,6 +449,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([setTriggerConditions: () => true,setModelConfiguration: () => true,setEvaluationType: () => true,+ setEvaluationTarget: () => true,+ setTraceWindowSeconds: () => true,setHogSource: () => true,saveEvaluationSuccess: () => false,loadEvaluationSuccess: () => false,@@ -480,6 +535,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([properties: [],},],+ target: 'generation' as const,+ target_config: {},model_configuration: null,total_runs: 0,created_at: new Date().toISOString(),@@ -579,6 +636,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([properties: [],},],+ target: 'generation',+ target_config: {},model_configuration: null,total_runs: 0,created_at: new Date().toISOString(),diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.tsindex 296174be8897..d24f1b558488 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts@@ -65,6 +65,8 @@ const evaluationWithKey = (id: string, providerKeyId: string | null): LLMJudgeEvoutput_type: 'boolean',output_config: {},conditions: [{ id: `cond-${id}`, rollout_percentage: 100, properties: [] }],+ target: 'generation',+ target_config: {},model_configuration: providerKeyId? {provider: 'openai',diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.tsindex b5cd5f870693..0060a285d7f9 100644--- a/products/ai_observability/frontend/evaluations/types.ts+++ b/products/ai_observability/frontend/evaluations/types.ts@@ -3,6 +3,7 @@ import { AnyPropertyFilter } from '~/types'import { LLMProvider } from '../settings/llmProviderKeysLogic'export type EvaluationType = 'llm_judge' | 'hog' | 'sentiment'+export type EvaluationTarget = 'generation' | 'trace'export type EvaluationOutputType = 'boolean' | 'sentiment'export type EvaluationStatus = 'active' | 'paused' | 'error'export type EvaluationStatusReason =@@ -28,6 +29,11 @@ export interface EvaluationOutputConfig {allows_na?: boolean}+export interface EvaluationTargetConfig {+ /** For 'trace' target: seconds to wait after the first matching generation before evaluating the trace. */+ window_seconds?: number+}+export interface LLMJudgeEvaluationConfig {prompt: string}@@ -52,6 +58,10 @@ export interface BaseEvaluationConfig {output_type: EvaluationOutputTypeoutput_config: EvaluationOutputConfigconditions: EvaluationConditionSet[]+ /** What the evaluation runs on: each matching generation event, or the whole trace once. */+ target: EvaluationTarget+ /** Target-specific settings. For 'trace': {window_seconds}. Empty for 'generation'. */+ target_config: EvaluationTargetConfigmodel_configuration: ModelConfiguration | nulltotal_runs: numberlast_run_at?: stringdiff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex ec819c4a07bb..0b0350017174 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -397,6 +397,17 @@ export interface EvaluationConditionApi {properties?: EvaluationConditionApiPropertiesItem[]}+/**+ * * `generation` - Generation+ * * `trace` - Trace+ */+export type EvaluationTargetEnumApi = (typeof EvaluationTargetEnumApi)[keyof typeof EvaluationTargetEnumApi]++export const EvaluationTargetEnumApi = {+ Generation: 'generation',+ Trace: 'trace',+} as const+/*** * `openai` - Openai* * `anthropic` - Anthropic@@ -467,6 +478,18 @@ export type EvaluationApiOutputConfig = {allows_na?: boolean}+/**+ * Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.+ */+export type EvaluationApiTargetConfig = {+ /**+ * For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight.+ * @minimum 10+ * @maximum 7200+ */+ window_seconds?: number+}+export interface EvaluationApi {readonly id: string/**@@ -502,6 +525,13 @@ export interface EvaluationApi {output_config?: EvaluationApiOutputConfig/** Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads. */conditions?: EvaluationConditionApi[]+ /** What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.+ *+ * * `generation` - Generation+ * * `trace` - Trace */+ target?: EvaluationTargetEnumApi+ /** Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'. */+ target_config?: EvaluationApiTargetConfigmodel_configuration?: ModelConfigurationApi | nullreadonly created_at: stringreadonly updated_at: string@@ -550,6 +580,18 @@ export type PatchedEvaluationApiOutputConfig = {allows_na?: boolean}+/**+ * Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.+ */+export type PatchedEvaluationApiTargetConfig = {+ /**+ * For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight.+ * @minimum 10+ * @maximum 7200+ */+ window_seconds?: number+}+export interface PatchedEvaluationApi {readonly id?: string/**@@ -585,6 +627,13 @@ export interface PatchedEvaluationApi {output_config?: PatchedEvaluationApiOutputConfig/** Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads. */conditions?: EvaluationConditionApi[]+ /** What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.+ *+ * * `generation` - Generation+ * * `trace` - Trace */+ target?: EvaluationTargetEnumApi+ /** Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'. */+ target_config?: PatchedEvaluationApiTargetConfigmodel_configuration?: ModelConfigurationApi | nullreadonly created_at?: stringreadonly updated_at?: stringdiff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.tsindex f0286baddcbf..52faa9145350 100644--- a/products/ai_observability/frontend/generated/api.zod.ts+++ b/products/ai_observability/frontend/generated/api.zod.ts@@ -112,6 +112,10 @@ export const evaluationsCreateBodyConditionsItemRolloutPercentageDefault = 100export const evaluationsCreateBodyConditionsItemRolloutPercentageMin = 0export const evaluationsCreateBodyConditionsItemRolloutPercentageMax = 100+export const evaluationsCreateBodyTargetConfigWindowSecondsDefault = 1800+export const evaluationsCreateBodyTargetConfigWindowSecondsMin = 10+export const evaluationsCreateBodyTargetConfigWindowSecondsMax = 7200+export const evaluationsCreateBodyModelConfigurationOneModelMax = 100export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({@@ -196,6 +200,26 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({.describe('Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'),+ target: zod+ .enum(['generation', 'trace'])+ .describe('\* `generation` - Generation\n\* `trace` - Trace')+ .optional()+ .describe(+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n\* `generation` - Generation\n\* `trace` - Trace"+ ),+ target_config: zod+ .object({+ window_seconds: zod+ .number()+ .min(evaluationsCreateBodyTargetConfigWindowSecondsMin)+ .max(evaluationsCreateBodyTargetConfigWindowSecondsMax)+ .default(evaluationsCreateBodyTargetConfigWindowSecondsDefault)+ .describe(+ "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight."+ ),+ })+ .optional()+ .describe("Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'."),model_configuration: zod.union([zod@@ -240,6 +264,10 @@ export const evaluationsUpdateBodyConditionsItemRolloutPercentageDefault = 100export const evaluationsUpdateBodyConditionsItemRolloutPercentageMin = 0export const evaluationsUpdateBodyConditionsItemRolloutPercentageMax = 100+export const evaluationsUpdateBodyTargetConfigWindowSecondsDefault = 1800+export const evaluationsUpdateBodyTargetConfigWindowSecondsMin = 10+export const evaluationsUpdateBodyTargetConfigWindowSecondsMax = 7200+export const evaluationsUpdateBodyModelConfigurationOneModelMax = 100export const EvaluationsUpdateBody = /* @__PURE__ */ zod.object({@@ -324,6 +352,26 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod.object({.describe('Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'),+ target: zod+ .enum(['generation', 'trace'])+ .describe('\* `generation` - Generation\n\* `trace` - Trace')+ .optional()+ .describe(+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n\* `generation` - Generation\n\* `trace` - Trace"+ ),+ target_config: zod+ .object({+ window_seconds: zod+ .number()+ .min(evaluationsUpdateBodyTargetConfigWindowSecondsMin)+ .max(evaluationsUpdateBodyTargetConfigWindowSecondsMax)+ .default(evaluationsUpdateBodyTargetConfigWindowSecondsDefault)+ .describe(+ "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight."+ ),+ })+ .optional()+ .describe("Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'."),model_configuration: zod.union([zod@@ -368,6 +416,10 @@ export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefaultexport const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMin = 0export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMax = 100+export const evaluationsPartialUpdateBodyTargetConfigWindowSecondsDefault = 1800+export const evaluationsPartialUpdateBodyTargetConfigWindowSecondsMin = 10+export const evaluationsPartialUpdateBodyTargetConfigWindowSecondsMax = 7200+export const evaluationsPartialUpdateBodyModelConfigurationOneModelMax = 100export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({@@ -454,6 +506,26 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'),+ target: zod+ .enum(['generation', 'trace'])+ .describe('\* `generation` - Generation\n\* `trace` - Trace')+ .optional()+ .describe(+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n\* `generation` - Generation\n\* `trace` - Trace"+ ),+ target_config: zod+ .object({+ window_seconds: zod+ .number()+ .min(evaluationsPartialUpdateBodyTargetConfigWindowSecondsMin)+ .max(evaluationsPartialUpdateBodyTargetConfigWindowSecondsMax)+ .default(evaluationsPartialUpdateBodyTargetConfigWindowSecondsDefault)+ .describe(+ "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight."+ ),+ })+ .optional()+ .describe("Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'."),model_configuration: zod.union([zoddiff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.pyindex 0a8d01a54da9..394ba6fddd8a 100644--- a/products/data_warehouse/backend/presentation/views/external_data_source.py+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py@@ -2542,12 +2542,12 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixitry:schemas = source.get_schemas(source_config, self.team_id)except Exception as e:- error_message, is_expected_source_error = _classify_refresh_schemas_error(source, e)+ _, is_expected_source_error = _classify_refresh_schemas_error(source, e)if not is_expected_source_error:capture_exception(e, {"source_type": source_type, "team_id": self.team_id})return Response(status=status.HTTP_400_BAD_REQUEST,- data={"message": error_message},+ data={"message": str(e)},)# Best-effort per-endpoint scope probe — transient failure falls back to "available".@@ -2658,10 +2658,8 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixidata={"message": f"Source type '{source_type}' does not support one-shot setup."},)except Exception as e:- error_message, is_expected_source_error = _classify_refresh_schemas_error(source, e)- if not is_expected_source_error:- capture_exception(e, {"source_type": source_type, "team_id": self.team_id})- return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": error_message})+ capture_exception(e, {"source_type": source_type, "team_id": self.team_id})+ return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": str(e)})if not source_schemas:return Response(diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.pyindex 724de5d4757c..cda5557dd5ba 100644--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py@@ -3898,57 +3898,6 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertIs(response.json()[0]["xmin_available"], expected_xmin_available)- @parameterized.expand(- [- ("database_schema", "database_schema/", {"source_type": "Stripe"}),- ("setup", "setup/", {"source_type": "Stripe", "payload": {}}),- ]- )- @patch("products.data_warehouse.backend.presentation.views.external_data_source.capture_exception")- @patch("products.data_warehouse.backend.presentation.views.external_data_source.SourceRegistry.get_source")- def test_schema_discovery_returns_friendly_message_for_expected_error(- self, _name, endpoint, body, mock_get_source, mock_capture_exception- ):- source = mock_get_source.return_value- source.validate_config.return_value = (True, [])- source.parse_config.return_value = Mock()- source.validate_credentials.return_value = (True, None)- source.get_non_retryable_errors.return_value = {}- source.get_schemas.side_effect = Exception("connection timed out")-- response = self.client.post(- f"/api/environments/{self.team.pk}/external_data_sources/{endpoint}",- data=body,- )-- self.assertEqual(response.status_code, 400)- self.assertEqual(- response.json().get("message"),- "Connection timed out while fetching schemas from the source.",- )- mock_capture_exception.assert_not_called()-- @patch("products.data_warehouse.backend.presentation.views.external_data_source.capture_exception")- @patch("products.data_warehouse.backend.presentation.views.external_data_source.SourceRegistry.get_source")- def test_setup_returns_generic_message_for_unexpected_error(self, mock_get_source, mock_capture_exception):- source = mock_get_source.return_value- source.validate_config.return_value = (True, [])- source.parse_config.return_value = Mock()- source.validate_credentials.return_value = (True, None)- source.get_non_retryable_errors.return_value = {}- raw_error = "psql: host=internal-db.prod user=admin password=hunter2 failed"- source.get_schemas.side_effect = Exception(raw_error)-- response = self.client.post(- f"/api/environments/{self.team.pk}/external_data_sources/setup/",- data={"source_type": "Stripe", "payload": {}},- )-- self.assertEqual(response.status_code, 400)- # Unrecognized errors must not leak the raw exception text (e.g. credentials) to the client.- self.assertEqual(response.json().get("message"), "Could not fetch schemas from source.")- mock_capture_exception.assert_called_once()-def test_database_schema(self):postgres_connection = psycopg.connect(host=settings.PG_HOST,@@ -4102,13 +4051,10 @@ class TestExternalDataSource(APIBaseTest):)assert response.status_code == 400+ assert response.json()["message"] == str(error)if expect_capture:- # Unrecognized errors return the generic fallback (never the raw exception text) and are captured.- assert response.json()["message"] == "Could not fetch schemas from source."mock_capture_exception.assert_called_once_with(error, {"source_type": "BigQuery", "team_id": self.team.pk})else:- # Recognized errors surface their curated, user-safe message.- assert response.json()["message"] == str(error)mock_capture_exception.assert_not_called()def test_database_schema_stripe_surfaces_per_endpoint_permission_errors(self):diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 24bb3e9c3315..897460913810 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -20051,6 +20051,18 @@ export namespace Schemas {allows_na?: boolean;};+ /**+ * Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.+ */+ export type EvaluationTargetConfig = {+ /**+ * For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight.+ * @minimum 10+ * @maximum 7200+ */+ window_seconds?: number;+ };+/*** * `active` - Active* * `paused` - Paused@@ -20140,6 +20152,18 @@ export namespace Schemas {properties?: EvaluationConditionPropertiesItem[];}+ /**+ * * `generation` - Generation+ * * `trace` - Trace+ */+ export type EvaluationTargetEnum = typeof EvaluationTargetEnum[keyof typeof EvaluationTargetEnum];+++ export const EvaluationTargetEnum = {+ Generation: 'generation',+ Trace: 'trace',+ } as const;+/*** * `openai` - Openai* * `anthropic` - Anthropic@@ -20215,6 +20239,13 @@ export namespace Schemas {output_config?: EvaluationOutputConfig;/** Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads. */conditions?: EvaluationCondition[];+ /** What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.+ *+ * * `generation` - Generation+ * * `trace` - Trace */+ target?: EvaluationTargetEnum;+ /** Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'. */+ target_config?: EvaluationTargetConfig;model_configuration?: ModelConfiguration | null;readonly created_at: string;readonly updated_at: string;@@ -36730,6 +36761,18 @@ export namespace Schemas {allows_na?: boolean;};+ /**+ * Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.+ */+ export type PatchedEvaluationTargetConfig = {+ /**+ * For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight.+ * @minimum 10+ * @maximum 7200+ */+ window_seconds?: number;+ };+export interface PatchedEvaluation {readonly id?: string;/**@@ -36765,6 +36808,13 @@ export namespace Schemas {output_config?: PatchedEvaluationOutputConfig;/** Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads. */conditions?: EvaluationCondition[];+ /** What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.+ *+ * * `generation` - Generation+ * * `trace` - Trace */+ target?: EvaluationTargetEnum;+ /** Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'. */+ target_config?: PatchedEvaluationTargetConfig;model_configuration?: ModelConfiguration | null;readonly created_at?: string;readonly updated_at?: string;diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.tsindex 12fd2dca8ac5..46887192cd4b 100644--- a/services/mcp/src/generated/ai_observability/api.ts+++ b/services/mcp/src/generated/ai_observability/api.ts@@ -133,6 +133,10 @@ export const evaluationsCreateBodyConditionsItemRolloutPercentageDefault = 100export const evaluationsCreateBodyConditionsItemRolloutPercentageMin = 0export const evaluationsCreateBodyConditionsItemRolloutPercentageMax = 100+export const evaluationsCreateBodyTargetConfigWindowSecondsDefault = 1800+export const evaluationsCreateBodyTargetConfigWindowSecondsMin = 10+export const evaluationsCreateBodyTargetConfigWindowSecondsMax = 7200+export const evaluationsCreateBodyModelConfigurationOneModelMax = 100export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({@@ -217,6 +221,26 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({.describe('Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'),+ target: zod+ .enum(['generation', 'trace'])+ .describe('* `generation` - Generation\n* `trace` - Trace')+ .optional()+ .describe(+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n* `generation` - Generation\n* `trace` - Trace"+ ),+ target_config: zod+ .object({+ window_seconds: zod+ .number()+ .min(evaluationsCreateBodyTargetConfigWindowSecondsMin)+ .max(evaluationsCreateBodyTargetConfigWindowSecondsMax)+ .default(evaluationsCreateBodyTargetConfigWindowSecondsDefault)+ .describe(+ "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight."+ ),+ })+ .optional()+ .describe("Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'."),model_configuration: zod.union([zod@@ -279,6 +303,10 @@ export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefaultexport const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMin = 0export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMax = 100+export const evaluationsPartialUpdateBodyTargetConfigWindowSecondsDefault = 1800+export const evaluationsPartialUpdateBodyTargetConfigWindowSecondsMin = 10+export const evaluationsPartialUpdateBodyTargetConfigWindowSecondsMax = 7200+export const evaluationsPartialUpdateBodyModelConfigurationOneModelMax = 100export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({@@ -365,6 +393,26 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'),+ target: zod+ .enum(['generation', 'trace'])+ .describe('* `generation` - Generation\n* `trace` - Trace')+ .optional()+ .describe(+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n* `generation` - Generation\n* `trace` - Trace"+ ),+ target_config: zod+ .object({+ window_seconds: zod+ .number()+ .min(evaluationsPartialUpdateBodyTargetConfigWindowSecondsMin)+ .max(evaluationsPartialUpdateBodyTargetConfigWindowSecondsMax)+ .default(evaluationsPartialUpdateBodyTargetConfigWindowSecondsDefault)+ .describe(+ "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight."+ ),+ })+ .optional()+ .describe("Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'."),model_configuration: zod.union([zoddiff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.tsindex ea47437fc92b..f9718fca9e15 100644--- a/services/mcp/src/tools/generated/ai_observability.ts+++ b/services/mcp/src/tools/generated/ai_observability.ts@@ -293,6 +293,12 @@ const llmaEvaluationCreate = (): ToolBase<typeof LlmaEvaluationCreateSchema, Schif (params.conditions !== undefined) {body['conditions'] = params.conditions}+ if (params.target !== undefined) {+ body['target'] = params.target+ }+ if (params.target_config !== undefined) {+ body['target_config'] = params.target_config+ }if (params.model_configuration !== undefined) {body['model_configuration'] = params.model_configuration}@@ -715,6 +721,12 @@ const llmaEvaluationUpdate = (): ToolBase<typeof LlmaEvaluationUpdateSchema, Schif (params.conditions !== undefined) {body['conditions'] = params.conditions}+ if (params.target !== undefined) {+ body['target'] = params.target+ }+ if (params.target_config !== undefined) {+ body['target_config'] = params.target_config+ }if (params.model_configuration !== undefined) {body['model_configuration'] = params.model_configuration}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.jsonindex f44cf974dba9..3ec43125507b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json@@ -165,6 +165,24 @@"description": "Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.\n\n* `boolean` - Boolean (Pass/Fail)\n* `sentiment` - Sentiment","enum": ["boolean", "sentiment"],"type": "string"+ },+ "target": {+ "description": "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n* `generation` - Generation\n* `trace` - Trace",+ "enum": ["generation", "trace"],+ "type": "string"+ },+ "target_config": {+ "description": "Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.",+ "properties": {+ "window_seconds": {+ "default": 1800,+ "description": "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight.",+ "maximum": 7200,+ "minimum": 10,+ "type": "number"+ }+ },+ "type": "object"}},"required": ["name", "evaluation_type", "output_type"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.jsonindex 4519bfe42e9b..a9e5494b051c 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json@@ -169,6 +169,24 @@"description": "Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.\n\n* `boolean` - Boolean (Pass/Fail)\n* `sentiment` - Sentiment","enum": ["boolean", "sentiment"],"type": "string"+ },+ "target": {+ "description": "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n* `generation` - Generation\n* `trace` - Trace",+ "enum": ["generation", "trace"],+ "type": "string"+ },+ "target_config": {+ "description": "Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.",+ "properties": {+ "window_seconds": {+ "default": 1800,+ "description": "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight.",+ "maximum": 7200,+ "minimum": 10,+ "type": "number"+ }+ },+ "type": "object"}},"required": ["id"],