Skip to content

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

feat(aio): evaluate whole sessions (#76041)

Carlos Marchal2f6206f015b7
diff --git a/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.test.ts b/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.test.ts
index 082affba531e..9e5d23c477e0 100644
--- a/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.test.ts
+++ b/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.test.ts
@@ -13,7 +13,7 @@ import {
checkConditionMatch,
checkRolloutPercentage,
eachBatchEvaluationScheduler,
- extractTraceContext,
+ extractEvaluationContext,
filterAndParseMessages,
groupEventsByTeam,
unwrapOrLog,
@@ -440,13 +440,21 @@ describe('Evaluation Scheduler', () => {
})
})
- describe('extractTraceContext', () => {
- it('extracts string trace and session ids', () => {
+ describe('extractEvaluationContext', () => {
+ it('extracts string trace, session, and ai session ids', () => {
const event = createAiGenerationEvent(teamId, {
- properties: JSON.stringify({ $ai_trace_id: 'trace-1', $session_id: 'session-1' }),
+ properties: JSON.stringify({
+ $ai_trace_id: 'trace-1',
+ $session_id: 'session-1',
+ $ai_session_id: 'ai-session-1',
+ }),
})
- expect(extractTraceContext(event)).toEqual({ traceId: 'trace-1', sessionId: 'session-1' })
+ expect(extractEvaluationContext(event)).toEqual({
+ traceId: 'trace-1',
+ sessionId: 'session-1',
+ aiSessionId: 'ai-session-1',
+ })
})
it('coerces numeric trace ids to strings', () => {
@@ -454,7 +462,7 @@ describe('Evaluation Scheduler', () => {
properties: JSON.stringify({ $ai_trace_id: 0 }),
})
- expect(extractTraceContext(event)).toEqual({ traceId: '0', sessionId: null })
+ expect(extractEvaluationContext(event)).toEqual({ traceId: '0', sessionId: null, aiSessionId: null })
})
it('returns nulls for missing or empty ids', () => {
@@ -462,13 +470,13 @@ describe('Evaluation Scheduler', () => {
properties: JSON.stringify({ $ai_trace_id: '', $ai_input: 'hi' }),
})
- expect(extractTraceContext(event)).toEqual({ traceId: null, sessionId: null })
+ expect(extractEvaluationContext(event)).toEqual({ traceId: null, sessionId: null, aiSessionId: null })
})
it('returns nulls on malformed properties JSON', () => {
const event = createAiGenerationEvent(teamId, { properties: 'not json{' })
- expect(extractTraceContext(event)).toEqual({ traceId: null, sessionId: null })
+ expect(extractEvaluationContext(event)).toEqual({ traceId: null, sessionId: null, aiSessionId: null })
})
})
@@ -543,11 +551,14 @@ describe('Evaluation Scheduler', () => {
await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService)
expect(temporalService.startAggregateEvaluationWorkflow).toHaveBeenCalledWith(
- 'eval-1',
- expect.objectContaining({ uuid: event.uuid }),
- 'trace-abc',
- null,
- { strategy: 'fixed_window', window_seconds: 900 }
+ expect.objectContaining({
+ evaluationId: 'eval-1',
+ event: expect.objectContaining({ uuid: event.uuid }),
+ target: 'trace',
+ traceId: 'trace-abc',
+ sessionId: null,
+ settle: { strategy: 'fixed_window', window_seconds: 900 },
+ })
)
expect(temporalService.startEvaluationRunWorkflow).not.toHaveBeenCalled()
})
@@ -567,11 +578,14 @@ describe('Evaluation Scheduler', () => {
await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService)
expect(temporalService.startAggregateEvaluationWorkflow).toHaveBeenCalledWith(
- 'eval-1',
- expect.objectContaining({ uuid: event.uuid }),
- 'trace-abc',
- null,
- { strategy: 'fixed_window', window_seconds: 1800 }
+ expect.objectContaining({
+ evaluationId: 'eval-1',
+ event: expect.objectContaining({ uuid: event.uuid }),
+ target: 'trace',
+ traceId: 'trace-abc',
+ sessionId: null,
+ settle: { strategy: 'fixed_window', window_seconds: 1800 },
+ })
)
expect(temporalService.startEvaluationRunWorkflow).not.toHaveBeenCalled()
})
@@ -591,11 +605,12 @@ describe('Evaluation Scheduler', () => {
await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService)
expect(temporalService.startAggregateEvaluationWorkflow).toHaveBeenCalledWith(
- evaluation.id,
- expect.anything(),
- expect.any(String),
- null,
- { strategy: 'inactivity', quiet_period_seconds: 120, max_age_seconds: 7200 }
+ expect.objectContaining({
+ evaluationId: evaluation.id,
+ target: 'trace',
+ sessionId: null,
+ settle: { strategy: 'inactivity', quiet_period_seconds: 120, max_age_seconds: 7200 },
+ })
)
})
@@ -636,6 +651,96 @@ describe('Evaluation Scheduler', () => {
)
expect(temporalService.startAggregateEvaluationWorkflow).not.toHaveBeenCalled()
})
+
+ it('dispatches a session evaluation keyed on $ai_session_id', async () => {
+ const event = createAiGenerationEvent(teamId, {
+ properties: JSON.stringify({
+ $ai_trace_id: 'trace-abc',
+ $ai_session_id: 'ai-session-9',
+ $session_id: 'ph-session-1',
+ }),
+ })
+ const evaluation = createEvaluation({
+ id: 'eval-1',
+ team_id: teamId,
+ target: 'session',
+ target_config: { strategy: 'inactivity', quiet_period_seconds: 3600, max_age_seconds: 86400 },
+ 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.startAggregateEvaluationWorkflow).toHaveBeenCalledWith(
+ expect.objectContaining({
+ evaluationId: 'eval-1',
+ target: 'session',
+ aiSessionId: 'ai-session-9',
+ sessionId: 'ph-session-1',
+ })
+ )
+ })
+
+ it('skips a session evaluation when the generation carries no $ai_session_id', async () => {
+ const event = createAiGenerationEvent(teamId, {
+ // $session_id is present and $ai_session_id is not. This is the common case: 100% of
+ // measured generations carry $session_id, only 7.4% carry $ai_session_id, and the two
+ // are never equal.
+ properties: JSON.stringify({ $ai_trace_id: 'trace-abc', $session_id: 'ph-session-1' }),
+ })
+ const evaluation = createEvaluation({
+ id: 'eval-1',
+ team_id: teamId,
+ target: 'session',
+ target_config: { strategy: 'inactivity', quiet_period_seconds: 3600, max_age_seconds: 86400 },
+ 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.startAggregateEvaluationWorkflow).not.toHaveBeenCalled()
+ expect(temporalService.startEvaluationRunWorkflow).not.toHaveBeenCalled()
+ })
+
+ it('samples a session atomically across its traces, keyed on the ai session id', async () => {
+ // A rollout below 100 must decide once per session, not once per trace. Driving two
+ // different session ids through a fixed 50% rollout and checking that every trace of
+ // a given session lands on the same in/out decision catches per-trace sampling: with
+ // per-trace sampling, checkRolloutPercentage would be called with each trace id
+ // individually and could split a single session's traces across both outcomes.
+ const evaluation = createEvaluation({
+ id: 'eval-1',
+ team_id: teamId,
+ target: 'session',
+ target_config: { strategy: 'inactivity', quiet_period_seconds: 3600, max_age_seconds: 86400 },
+ conditions: [createEvaluationCondition({ bytecode: ['_H', 1, 32, true], rollout_percentage: 50 })],
+ })
+ ;(evaluationManager.getEvaluationsForTeams as jest.Mock).mockResolvedValue({ [teamId]: [evaluation] })
+
+ const sessionIds = ['ai-session-in', 'ai-session-out']
+ const [includedSessionId, excludedSessionId] = sessionIds
+ .map((id) => [id, checkRolloutPercentage(id, 50)] as const)
+ .sort(([, aIncluded], [, bIncluded]) => Number(bIncluded) - Number(aIncluded))
+ .map(([id]) => id)
+
+ const messages = ['trace-1', 'trace-2', 'trace-3'].map((traceId, i) =>
+ messageFor(
+ createAiGenerationEvent(teamId, {
+ properties: JSON.stringify({
+ $ai_trace_id: traceId,
+ $ai_session_id: i < 2 ? includedSessionId : excludedSessionId,
+ }),
+ })
+ )
+ )
+ await eachBatchEvaluationScheduler(messages, evaluationManager, taggerManager, temporalService)
+
+ const calls = (temporalService.startAggregateEvaluationWorkflow as jest.Mock).mock.calls
+ const dispatchedSessionIds = calls.map(([options]) => options.aiSessionId)
+
+ expect(dispatchedSessionIds).toEqual([includedSessionId, includedSessionId])
+ })
})
describe('eachBatchEvaluationScheduler batching', () => {
diff --git a/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.ts b/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.ts
index c77a177892a0..6f6533ead047 100644
--- a/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.ts
+++ b/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.ts
@@ -50,7 +50,7 @@ const evaluationSchedulerEventsProcessed = new Counter({
const evaluationMatchesCounter = new Counter({
name: 'evaluation_matches',
help: 'Number of evaluation matches by outcome',
- labelNames: ['outcome', 'type'], // matched, filtered, sampling_excluded, error × evaluation/tagger
+ labelNames: ['outcome', 'type'], // matched, filtered, sampling_excluded, error × evaluation/tagger; no_ai_session_id on evaluation only
})
const evaluationSchedulerMessagesReceived = new Counter({
@@ -123,22 +123,31 @@ export function groupEventsByTeam(events: RawKafkaEvent[]): Map<number, RawKafka
}
/**
- * Pull the trace linkage out of an event's properties. Trace ids are user-controlled and can
+ * Pull the evaluation-unit linkage out of an event's properties. 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.
+ *
+ * `sessionId` ($session_id) is PostHog's product-analytics session and only ever travels through
+ * to the emitted evaluation event. `aiSessionId` ($ai_session_id) is the AI-observability session
+ * and is the unit a session-target evaluation runs on. They are different id spaces.
*/
-export function extractTraceContext(event: RawKafkaEvent): { traceId: string | null; sessionId: string | null } {
+export function extractEvaluationContext(event: RawKafkaEvent): {
+ traceId: string | null
+ sessionId: string | null
+ aiSessionId: string | null
+} {
let properties: Record<string, unknown> = {}
try {
properties = parseJSON(event.properties || '{}')
} catch {
- return { traceId: null, sessionId: null }
+ return { traceId: null, sessionId: null, aiSessionId: 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']),
+ aiSessionId: coerce(properties['$ai_session_id']),
}
}
@@ -439,21 +448,26 @@ async function processEventEvaluationMatch(
): Promise<void> {
evaluationSchedulerEventsProcessed.labels({ status: 'received', type: 'evaluation' }).inc()
- const isTraceTarget = evaluationDefinition.target === 'trace'
- let traceContext: ReturnType<typeof extractTraceContext> | null = null
- if (isTraceTarget) {
- traceContext = extractTraceContext(event)
- if (!traceContext.traceId) {
+ const target = evaluationDefinition.target
+ const isAggregateTarget = target === 'trace' || target === 'session'
+ let context: ReturnType<typeof extractEvaluationContext> | null = null
+ if (isAggregateTarget) {
+ context = extractEvaluationContext(event)
+ if (!context.traceId) {
evaluationMatchesCounter.labels({ outcome: 'no_trace_id', type: 'evaluation' }).inc()
return
}
+ if (target === 'session' && !context.aiSessionId) {
+ // Expected for any producer that doesn't set $ai_session_id (most of them). This
+ // counter is the coverage signal for whether session evals can fire at all.
+ evaluationMatchesCounter.labels({ outcome: 'no_ai_session_id', type: 'evaluation' }).inc()
+ return
+ }
}
- const result = await matcher.shouldTriggerEvaluation(
- event,
- evaluationDefinition,
- traceContext?.traceId ?? undefined
- )
+ // Sample per unit so a whole trace, or a whole session, is atomically in or out.
+ const samplingKey = target === 'session' ? context?.aiSessionId : context?.traceId
+ const result = await matcher.shouldTriggerEvaluation(event, evaluationDefinition, samplingKey ?? undefined)
if (!result.matched) {
evaluationMatchesCounter.labels({ outcome: result.reason, type: 'evaluation' }).inc()
@@ -469,23 +483,25 @@ async function processEventEvaluationMatch(
logger.debug('Evaluation matched, enqueueing evaluation run', {
evaluationId: evaluationDefinition.id,
eventUuid: event.uuid,
- traceId: traceContext?.traceId,
+ traceId: context?.traceId,
+ aiSessionId: context?.aiSessionId,
conditionId: result.conditionId,
})
evaluationMatchesCounter.labels({ outcome: 'matched', type: 'evaluation' }).inc()
- if (isTraceTarget && traceContext?.traceId) {
+ if (isAggregateTarget && context?.traceId) {
// No isEvaluationWorkflowRuntime guard here: the aggregate workflow validates evaluation_type
// server-side and rejects unsupported types as a non-retryable ApplicationError.
- const settle = resolveSettleConfig(evaluationDefinition.target_config)
- await temporalService.startAggregateEvaluationWorkflow(
- evaluationDefinition.id,
+ await temporalService.startAggregateEvaluationWorkflow({
+ evaluationId: evaluationDefinition.id,
event,
- traceContext.traceId,
- traceContext.sessionId,
- settle
- )
+ target,
+ traceId: context.traceId,
+ sessionId: context.sessionId,
+ aiSessionId: context.aiSessionId,
+ settle: resolveSettleConfig(evaluationDefinition.target_config, target),
+ })
} else {
const evaluationRuntime = evaluationDefinition.evaluation_type
if (!isEvaluationWorkflowRuntime(evaluationRuntime)) {
diff --git a/nodejs/src/ai-observability/services/temporal.service.test.ts b/nodejs/src/ai-observability/services/temporal.service.test.ts
index 1675e3d5472b..314c5240c5f9 100644
--- a/nodejs/src/ai-observability/services/temporal.service.test.ts
+++ b/nodejs/src/ai-observability/services/temporal.service.test.ts
@@ -3,7 +3,7 @@ import { Client, Connection, WorkflowExecutionAlreadyStartedError } from '@tempo
import { EncryptionCodec } from '~/common/temporal/codec'
import { RawKafkaEvent } from '~/types'
-import { TemporalService, resolveSettleConfig, workflowSafeTraceId } from './temporal.service'
+import { TemporalService, resolveSettleConfig, workflowSafeId } from './temporal.service'
import type { EvaluationWorkflowRuntime, TemporalServiceConfig } from './temporal.service'
jest.mock('@temporalio/client')
@@ -280,10 +280,14 @@ describe('TemporalService', () => {
it('starts the aggregate workflow with the resolved settle config', async () => {
const mockEvent = createMockEvent()
- await service.startAggregateEvaluationWorkflow('eval-123', mockEvent, 'trace-abc', 'session-1', {
- strategy: 'inactivity',
- quiet_period_seconds: 120,
- max_age_seconds: 600,
+ await service.startAggregateEvaluationWorkflow({
+ evaluationId: 'eval-123',
+ event: mockEvent,
+ target: 'trace',
+ traceId: 'trace-abc',
+ sessionId: 'session-1',
+ aiSessionId: null,
+ settle: { strategy: 'inactivity', quiet_period_seconds: 120, max_age_seconds: 600 },
})
expect(mockClient.workflow.start).toHaveBeenCalledWith('run-aggregate-evaluation', {
@@ -294,6 +298,8 @@ describe('TemporalService', () => {
trace_id: 'trace-abc',
distinct_id: mockEvent.distinct_id,
session_id: 'session-1',
+ ai_session_id: null,
+ target: 'trace',
settle: { strategy: 'inactivity', quiet_period_seconds: 120, max_age_seconds: 600 },
},
],
@@ -305,37 +311,94 @@ describe('TemporalService', () => {
})
})
+ it('keys the session workflow on the ai session id, not the product-analytics session id', async () => {
+ const mockEvent = createMockEvent()
+
+ await service.startAggregateEvaluationWorkflow({
+ evaluationId: 'eval-123',
+ event: mockEvent,
+ target: 'session',
+ traceId: 'trace-abc',
+ sessionId: 'ph-session-1',
+ aiSessionId: 'ai-session-9',
+ settle: { strategy: 'inactivity', quiet_period_seconds: 3600, max_age_seconds: 86400 },
+ })
+
+ expect(mockClient.workflow.start).toHaveBeenCalledWith('run-aggregate-evaluation', {
+ args: [
+ {
+ evaluation_id: 'eval-123',
+ team_id: mockEvent.team_id,
+ trace_id: 'trace-abc',
+ distinct_id: mockEvent.distinct_id,
+ session_id: 'ph-session-1',
+ ai_session_id: 'ai-session-9',
+ target: 'session',
+ settle: { strategy: 'inactivity', quiet_period_seconds: 3600, max_age_seconds: 86400 },
+ },
+ ],
+ taskQueue: 'llm-analytics-evals-task-queue',
+ workflowId: 'llma-session-eval-eval-123-ai-session-9',
+ workflowIdConflictPolicy: 'USE_EXISTING',
+ workflowIdReusePolicy: 'ALLOW_DUPLICATE_FAILED_ONLY',
+ workflowTaskTimeout: '2 minutes',
+ })
+ })
+
+ it('collapses every trace of one session onto the same workflow id', async () => {
+ for (const traceId of ['trace-1', 'trace-2']) {
+ await service.startAggregateEvaluationWorkflow({
+ evaluationId: 'eval-123',
+ event: createMockEvent(),
+ target: 'session',
+ traceId,
+ sessionId: null,
+ aiSessionId: 'ai-session-9',
+ settle: { strategy: 'inactivity', quiet_period_seconds: 3600, max_age_seconds: 86400 },
+ })
+ }
+
+ const calls = (mockClient.workflow.start as jest.Mock).mock.calls
+ expect(calls[0][1].workflowId).toEqual(calls[1][1].workflowId)
+ })
+
it('returns null when the trace was already evaluated', async () => {
;(mockClient.workflow.start as jest.Mock).mockRejectedValueOnce(
new WorkflowExecutionAlreadyStartedError('done', 'llma-trace-eval-x', 'run-aggregate-evaluation')
)
- const result = await service.startAggregateEvaluationWorkflow(
- 'eval-123',
- createMockEvent(),
- 'trace-abc',
- null,
- { strategy: 'fixed_window', window_seconds: 1800 }
- )
+ const result = await service.startAggregateEvaluationWorkflow({
+ evaluationId: 'eval-123',
+ event: createMockEvent(),
+ target: 'trace',
+ traceId: 'trace-abc',
+ sessionId: null,
+ aiSessionId: null,
+ settle: { strategy: 'fixed_window', window_seconds: 1800 },
+ })
expect(result).toBeNull()
})
it('produces the same workflow id for every event of the same trace', async () => {
- await service.startAggregateEvaluationWorkflow(
- 'eval-123',
- createMockEvent({ uuid: 'event-1' }),
- 'trace-789',
- null,
- { strategy: 'fixed_window', window_seconds: 1800 }
- )
- await service.startAggregateEvaluationWorkflow(
- 'eval-123',
- createMockEvent({ uuid: 'event-2' }),
- 'trace-789',
- null,
- { strategy: 'fixed_window', window_seconds: 1800 }
- )
+ await service.startAggregateEvaluationWorkflow({
+ evaluationId: 'eval-123',
+ event: createMockEvent({ uuid: 'event-1' }),
+ target: 'trace',
+ traceId: 'trace-789',
+ sessionId: null,
+ aiSessionId: null,
+ settle: { strategy: 'fixed_window', window_seconds: 1800 },
+ })
+ await service.startAggregateEvaluationWorkflow({
+ evaluationId: 'eval-123',
+ event: createMockEvent({ uuid: 'event-2' }),
+ target: 'trace',
+ traceId: 'trace-789',
+ sessionId: null,
+ aiSessionId: null,
+ settle: { strategy: 'fixed_window', window_seconds: 1800 },
+ })
const calls = (mockClient.workflow.start as jest.Mock).mock.calls
expect(calls[0][1].workflowId).toEqual(calls[1][1].workflowId)
@@ -346,9 +409,14 @@ describe('TemporalService', () => {
;(mockClient.workflow.start as jest.Mock).mockRejectedValue(new Error('Temporal unavailable'))
await expect(
- service.startAggregateEvaluationWorkflow('eval-123', createMockEvent(), 'trace-789', null, {
- strategy: 'fixed_window',
- window_seconds: 1800,
+ service.startAggregateEvaluationWorkflow({
+ evaluationId: 'eval-123',
+ event: createMockEvent(),
+ target: 'trace',
+ traceId: 'trace-789',
+ sessionId: null,
+ aiSessionId: null,
+ settle: { strategy: 'fixed_window', window_seconds: 1800 },
})
).rejects.toThrow('Temporal unavailable')
})
@@ -356,39 +424,52 @@ describe('TemporalService', () => {
describe('resolveSettleConfig', () => {
it.each([
- [undefined, { strategy: 'fixed_window', window_seconds: 1800 }],
- [{}, { strategy: 'fixed_window', window_seconds: 1800 }],
- [{ window_seconds: 60 }, { strategy: 'fixed_window', window_seconds: 60 }],
- [
- { strategy: 'fixed_window' as const, window_seconds: 900 },
- { strategy: 'fixed_window', window_seconds: 900 },
- ],
+ // Trace keeps its fixed_window fallback: rows saved before strategies existed mean that.
+ ['trace' as const, undefined, { strategy: 'fixed_window', window_seconds: 1800 }],
+ ['trace' as const, {}, { strategy: 'fixed_window', window_seconds: 1800 }],
[
+ 'trace' as const,
{ strategy: 'inactivity' as const },
{ strategy: 'inactivity', quiet_period_seconds: 300, max_age_seconds: 7200 },
],
+ // Sessions have no legacy rows, so a session config is always complete server-side and
+ // must never pick up the trace fallbacks.
+ [
+ 'session' as const,
+ { strategy: 'inactivity' as const, quiet_period_seconds: 86400, max_age_seconds: 604800 },
+ { strategy: 'inactivity', quiet_period_seconds: 86400, max_age_seconds: 604800 },
+ ],
[
- { strategy: 'inactivity' as const, quiet_period_seconds: 60, max_age_seconds: 600 },
- { strategy: 'inactivity', quiet_period_seconds: 60, max_age_seconds: 600 },
+ 'session' as const,
+ { strategy: 'fixed_window' as const, window_seconds: 604800 },
+ { strategy: 'fixed_window', window_seconds: 604800 },
],
- ])('resolves %j', (input, expected) => {
- expect(resolveSettleConfig(input)).toEqual(expected)
+ ])('resolves %s %j', (target, input, expected) => {
+ expect(resolveSettleConfig(input, target)).toEqual(expected)
+ })
+
+ it('does not apply trace fallbacks to an incomplete session config', () => {
+ expect(resolveSettleConfig({ strategy: 'inactivity' }, 'session')).toEqual({
+ strategy: 'inactivity',
+ quiet_period_seconds: 3600,
+ max_age_seconds: 86400,
+ })
})
})
- describe('workflowSafeTraceId', () => {
- it('keeps short trace ids as-is', () => {
- expect(workflowSafeTraceId('trace-789')).toBe('trace-789')
+ describe('workflowSafeId', () => {
+ it('keeps short ids as-is', () => {
+ expect(workflowSafeId('trace-789')).toBe('trace-789')
})
- it('hashes oversized trace ids deterministically', () => {
- const longTraceId = 'x'.repeat(500)
+ it('hashes oversized ids deterministically', () => {
+ const longId = 'x'.repeat(500)
- const safeId = workflowSafeTraceId(longTraceId)
+ const safeId = workflowSafeId(longId)
expect(safeId).toHaveLength(32)
- expect(safeId).toBe(workflowSafeTraceId(longTraceId))
- expect(safeId).not.toBe(workflowSafeTraceId(`${longTraceId}y`))
+ expect(safeId).toBe(workflowSafeId(longId))
+ expect(safeId).not.toBe(workflowSafeId(`${longId}y`))
})
})
})
diff --git a/nodejs/src/ai-observability/services/temporal.service.ts b/nodejs/src/ai-observability/services/temporal.service.ts
index 6fc2d76e34f6..25d3a3d35516 100644
--- a/nodejs/src/ai-observability/services/temporal.service.ts
+++ b/nodejs/src/ai-observability/services/temporal.service.ts
@@ -16,7 +16,7 @@ import { logger } from '~/common/utils/logger'
import { RawKafkaEvent } from '../../types'
import { AIObservabilityConfig } from '../config'
-import { EvaluationTargetConfig, ResolvedSettleConfig } from '../types'
+import { EvaluationTarget, EvaluationTargetConfig, ResolvedSettleConfig } from '../types'
export type TemporalServiceConfig = Pick<
AIObservabilityConfig,
@@ -57,17 +57,40 @@ export const DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS = 30 * 60
export const DEFAULT_TRACE_EVALUATION_QUIET_PERIOD_SECONDS = 5 * 60
export const DEFAULT_TRACE_EVALUATION_MAX_AGE_SECONDS = 2 * 60 * 60
-export function resolveSettleConfig(targetConfig: EvaluationTargetConfig | null | undefined): ResolvedSettleConfig {
+// Sessions have no strategy-less legacy rows — validate_target_config persists a complete config —
+// so these only ever fill a field the API somehow omitted, and must not be the trace values.
+export const DEFAULT_SESSION_EVALUATION_WINDOW_SECONDS = 30 * 60
+export const DEFAULT_SESSION_EVALUATION_QUIET_PERIOD_SECONDS = 60 * 60
+export const DEFAULT_SESSION_EVALUATION_MAX_AGE_SECONDS = 24 * 60 * 60
+
+const SETTLE_DEFAULTS = {
+ trace: {
+ window: DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS,
+ quiet: DEFAULT_TRACE_EVALUATION_QUIET_PERIOD_SECONDS,
+ maxAge: DEFAULT_TRACE_EVALUATION_MAX_AGE_SECONDS,
+ },
+ session: {
+ window: DEFAULT_SESSION_EVALUATION_WINDOW_SECONDS,
+ quiet: DEFAULT_SESSION_EVALUATION_QUIET_PERIOD_SECONDS,
+ maxAge: DEFAULT_SESSION_EVALUATION_MAX_AGE_SECONDS,
+ },
+} as const
+
+export function resolveSettleConfig(
+ targetConfig: EvaluationTargetConfig | null | undefined,
+ target: EvaluationTarget = 'trace'
+): ResolvedSettleConfig {
+ const defaults = target === 'session' ? SETTLE_DEFAULTS.session : SETTLE_DEFAULTS.trace
if (targetConfig?.strategy === 'inactivity') {
return {
strategy: 'inactivity',
- quiet_period_seconds: targetConfig.quiet_period_seconds ?? DEFAULT_TRACE_EVALUATION_QUIET_PERIOD_SECONDS,
- max_age_seconds: targetConfig.max_age_seconds ?? DEFAULT_TRACE_EVALUATION_MAX_AGE_SECONDS,
+ quiet_period_seconds: targetConfig.quiet_period_seconds ?? defaults.quiet,
+ max_age_seconds: targetConfig.max_age_seconds ?? defaults.maxAge,
}
}
return {
strategy: 'fixed_window',
- window_seconds: targetConfig?.window_seconds ?? DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS,
+ window_seconds: targetConfig?.window_seconds ?? defaults.window,
}
}
@@ -77,16 +100,26 @@ const temporalWorkflowsStarted = new Counter({
labelNames: ['status'],
})
+export interface AggregateEvaluationStart {
+ evaluationId: string
+ event: RawKafkaEvent
+ target: 'trace' | 'session'
+ traceId: string
+ sessionId: string | null
+ aiSessionId: string | null
+ settle: ResolvedSettleConfig
+}
+
/**
- * 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
+ * Trace and session 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
+export function workflowSafeId(id: string): string {
+ if (id.length <= 128) {
+ return id
}
- return crypto.createHash('md5').update(traceId).digest('hex')
+ return crypto.createHash('md5').update(id).digest('hex')
}
export class TemporalService {
@@ -228,26 +261,27 @@ export class TemporalService {
}
/**
- * Start (or join) the settle-then-evaluate workflow for (evaluation, trace).
+ * Start (or join) the settle-then-evaluate workflow for (evaluation, unit), where the unit is
+ * a trace or an $ai_session_id session.
*
- * 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). The workflow discovers further trace activity itself by polling
- * ClickHouse, so ingestion volume never reaches Temporal beyond this one dedup'd start.
- * 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.
+ * The workflow id deliberately excludes the event uuid: the first matching generation of the
+ * unit creates the workflow and every later one lands on it as a no-op (USE_EXISTING while
+ * pending/running). For a session that means every trace of the session collapses onto one
+ * workflow. The workflow discovers further activity itself by polling ClickHouse, so ingestion
+ * volume never reaches Temporal beyond this one dedup'd start. Once a run completed,
+ * ALLOW_DUPLICATE_FAILED_ONLY rejects new starts — a unit is evaluated at most once per
+ * evaluation for as long as the closed workflow stays inside Temporal's retention window,
+ * which also caps the damage from runaway shared ids ("0", "fixed_id", ...). Returns null when
+ * the unit was already evaluated.
*/
- async startAggregateEvaluationWorkflow(
- evaluationId: string,
- event: RawKafkaEvent,
- traceId: string,
- sessionId: string | null,
- settle: ResolvedSettleConfig
- ): Promise<WorkflowHandle | null> {
+ async startAggregateEvaluationWorkflow(options: AggregateEvaluationStart): Promise<WorkflowHandle | null> {
+ const { evaluationId, event, target, traceId, sessionId, aiSessionId, settle } = options
const client = await this.ensureConnected()
- const workflowId = `llma-trace-eval-${evaluationId}-${workflowSafeTraceId(traceId)}`
+ const workflowId =
+ target === 'session'
+ ? `llma-session-eval-${evaluationId}-${workflowSafeId(aiSessionId ?? '')}`
+ : `llma-trace-eval-${evaluationId}-${workflowSafeId(traceId)}`
try {
const handle = await client.workflow.start('run-aggregate-evaluation', {
@@ -258,6 +292,8 @@ export class TemporalService {
trace_id: traceId,
distinct_id: event.distinct_id,
session_id: sessionId,
+ ai_session_id: aiSessionId,
+ target,
settle,
},
],
@@ -273,7 +309,9 @@ export class TemporalService {
logger.debug('Started aggregate evaluation workflow', {
workflowId,
evaluationId,
+ target,
traceId,
+ aiSessionId,
strategy: settle.strategy,
timestamp: event.timestamp,
})
diff --git a/nodejs/src/ai-observability/types.ts b/nodejs/src/ai-observability/types.ts
index 77ec89d11f3e..7c14c97dee10 100644
--- a/nodejs/src/ai-observability/types.ts
+++ b/nodejs/src/ai-observability/types.ts
@@ -13,7 +13,7 @@ export type EvaluationStatusReason =
| 'provider_key_rate_limited'
| 'model_not_found'
| 'hog_error'
-export type EvaluationTarget = 'generation' | 'trace'
+export type EvaluationTarget = 'generation' | 'trace' | 'session'
export type EvaluationSettleStrategy = 'fixed_window' | 'inactivity'
/** Settle config stored on the evaluation. Rows saved before strategies existed have no
diff --git a/posthog/hogql_queries/ai/session_query_runner.py b/posthog/hogql_queries/ai/session_query_runner.py
index 5d07c1088304..314a90e728e4 100644
--- a/posthog/hogql_queries/ai/session_query_runner.py
+++ b/posthog/hogql_queries/ai/session_query_runner.py
@@ -64,7 +64,11 @@ class SessionQueryRunner(AnalyticsQueryRunner[SessionQueryResponse]):
cached_response: CachedSessionQueryResponse
paginator: HogQLHasMorePaginator
- def __init__(self, *args: Any, **kwargs: Any) -> None:
+ def __init__(self, *args: Any, for_evaluation: bool = False, **kwargs: Any) -> None:
+ # Online evaluations need a time-bounded primary query and no events fallback: an
+ # aged-out session must surface as "expired", not as a stripped events scan whose rows
+ # lack input/output_choices, which would have the judge grade an empty transcript.
+ self.for_evaluation = for_evaluation
super().__init__(*args, **kwargs)
limit = self.query.limit
if self.limit_context == LimitContext.EXPORT:
@@ -78,6 +82,9 @@ class SessionQueryRunner(AnalyticsQueryRunner[SessionQueryResponse]):
)
def _calculate(self) -> SessionQueryResponse:
+ if self.for_evaluation and not self._has_bounded_date_range():
+ raise ValueError("Evaluation-mode session queries require dateRange.date_from and dateRange.date_to")
+
query = self._build_query()
with self.timings.measure("session_query_ai_events_execute"), tags_context(product=Product.LLM_ANALYTICS):
@@ -96,7 +103,7 @@ class SessionQueryRunner(AnalyticsQueryRunner[SessionQueryResponse]):
limit_context=self.limit_context,
)
- if not query_result.results:
+ if not query_result.results and not self.for_evaluation:
fallback_filters = self._get_events_fallback_filters()
if fallback_filters is None:
return self._response_from_query_result(query_result, [])
@@ -277,18 +284,40 @@ class SessionQueryRunner(AnalyticsQueryRunner[SessionQueryResponse]):
def _has_fallback_date_range(self) -> bool:
return bool(self.query.dateRange and self.query.dateRange.date_from)
- def _get_trace_filter(self) -> ast.Expr:
+ def _has_bounded_date_range(self) -> bool:
+ # date_to must be explicit too: QueryDateRange defaults a missing date_to to now(),
+ # which would silently turn a half-open range into an unbounded upper bound.
+ return bool(self.query.dateRange and self.query.dateRange.date_from and self.query.dateRange.date_to)
+
+ def _date_filter(self) -> ast.Expr:
return ast.And(
exprs=[
- ast.Call(name="isNotNull", args=[ast.Field(chain=["ai_events", "trace_id"])]),
ast.CompareOperation(
- op=ast.CompareOperationOp.NotEq,
- left=ast.Field(chain=["ai_events", "trace_id"]),
- right=ast.Constant(value=""),
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["ai_events", "timestamp"]),
+ right=self._date_range.date_from_as_hogql(),
),
- ]
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.LtEq,
+ left=ast.Field(chain=["ai_events", "timestamp"]),
+ right=self._date_range.date_to_as_hogql(),
+ ),
+ ],
)
+ def _get_trace_filter(self) -> ast.Expr:
+ exprs: list[ast.Expr] = [
+ ast.Call(name="isNotNull", args=[ast.Field(chain=["ai_events", "trace_id"])]),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.NotEq,
+ left=ast.Field(chain=["ai_events", "trace_id"]),
+ right=ast.Constant(value=""),
+ ),
+ ]
+ if self.for_evaluation:
+ exprs.append(self._date_filter())
+ return ast.And(exprs=exprs)
+
def _get_session_filter(self) -> ast.Expr:
return ast.And(
exprs=[
@@ -306,20 +335,7 @@ class SessionQueryRunner(AnalyticsQueryRunner[SessionQueryResponse]):
if not self._has_fallback_date_range():
return None
- date_filter = ast.And(
- exprs=[
- ast.CompareOperation(
- op=ast.CompareOperationOp.GtEq,
- left=ast.Field(chain=["ai_events", "timestamp"]),
- right=self._date_range.date_from_as_hogql(),
- ),
- ast.CompareOperation(
- op=ast.CompareOperationOp.LtEq,
- left=ast.Field(chain=["ai_events", "timestamp"]),
- right=self._date_range.date_to_as_hogql(),
- ),
- ],
- )
+ date_filter = self._date_filter()
return (
ast.And(exprs=[self._get_session_filter(), date_filter]),
ast.And(exprs=[self._get_trace_filter(), date_filter]),
diff --git a/posthog/hogql_queries/ai/test/test_session_query_runner.py b/posthog/hogql_queries/ai/test/test_session_query_runner.py
index 240bc3ccbca4..796ba3b0b4af 100644
--- a/posthog/hogql_queries/ai/test/test_session_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_session_query_runner.py
@@ -3,10 +3,16 @@ from typing import Any
from posthog.test.base import BaseTest, ClickhouseTestMixin
+from parameterized import parameterized
+
from posthog.schema import DateRange, SessionQuery
from posthog.hogql.constants import MAX_SELECT_TRACES_LIMIT_EXPORT, LimitContext
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.placeholders import replace_placeholders
+from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql_queries.ai.ai_property_rewriter import rewrite_expr_for_ai_events_table
from posthog.hogql_queries.ai.session_query_runner import SessionQueryRunner
from posthog.models import Team
from posthog.models.ai_events.test_util import bulk_create_ai_events
@@ -336,3 +342,92 @@ class TestSessionQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertEqual(trace.outputTokens, 2)
self.assertAlmostEqual(trace.totalCost or 0, 0.01)
self.assertEqual(trace.totalLatency, 3)
+
+ def _printed_sql(self, runner: SessionQueryRunner) -> str:
+ query = replace_placeholders(
+ runner.to_query(),
+ {
+ "session_filter_conditions": rewrite_expr_for_ai_events_table(runner._get_session_filter()),
+ "trace_filter_conditions": rewrite_expr_for_ai_events_table(runner._get_trace_filter()),
+ },
+ )
+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)
+ sql, _ = prepare_and_print_ast(query, context, "clickhouse")
+ return sql
+
+ def test_evaluation_mode_bounds_the_primary_query(self) -> None:
+ runner = SessionQueryRunner(
+ team=self.team,
+ query=SessionQuery(
+ sessionId="s-1",
+ dateRange=DateRange(date_from="2026-07-01T00:00:00Z", date_to="2026-07-08T00:00:00Z"),
+ ),
+ for_evaluation=True,
+ )
+ sql = self._printed_sql(runner)
+
+ self.assertIn("greaterOrEquals(ai_events.timestamp", sql)
+ self.assertIn("lessOrEquals(ai_events.timestamp", sql)
+
+ default_runner = SessionQueryRunner(
+ team=self.team,
+ query=SessionQuery(
+ sessionId="s-1",
+ dateRange=DateRange(date_from="2026-07-01T00:00:00Z", date_to="2026-07-08T00:00:00Z"),
+ ),
+ )
+ default_sql = self._printed_sql(default_runner)
+
+ self.assertNotIn("greaterOrEquals(ai_events.timestamp", default_sql)
+ self.assertNotIn("lessOrEquals(ai_events.timestamp", default_sql)
+
+ @parameterized.expand(
+ [
+ ("missing_date_from", DateRange(date_to="2026-07-08T00:00:00Z")),
+ ("missing_date_to", DateRange(date_from="2026-07-01T00:00:00Z")),
+ ("missing_date_range", None),
+ ]
+ )
+ def test_evaluation_mode_requires_both_date_bounds(self, _name: str, date_range: DateRange | None) -> None:
+ runner = SessionQueryRunner(
+ team=self.team,
+ query=SessionQuery(sessionId="s-1", dateRange=date_range),
+ for_evaluation=True,
+ )
+ with self.assertRaises(ValueError):
+ runner.calculate()
+
+ def test_evaluation_mode_does_not_fall_back_to_events(self) -> None:
+ runner = SessionQueryRunner(
+ team=self.team,
+ query=SessionQuery(
+ sessionId="s-does-not-exist",
+ dateRange=DateRange(date_from="2026-07-01T00:00:00Z", date_to="2026-07-08T00:00:00Z"),
+ ),
+ for_evaluation=True,
+ )
+
+ with self.capture_select_queries() as queries:
+ response = runner.calculate()
+
+ select_queries = _select_queries_without_metadata(queries)
+ self.assertEqual(len(select_queries), 1)
+ self.assertNotIn("__ai_events_fallback", select_queries[0])
+ self.assertEqual(response.results, [])
+
+ def test_default_mode_still_falls_back_to_events(self) -> None:
+ """Regression guard: the session detail scene depends on the fallback."""
+ runner = SessionQueryRunner(
+ team=self.team,
+ query=SessionQuery(
+ sessionId="s-does-not-exist",
+ dateRange=DateRange(date_from="2026-07-01T00:00:00Z", date_to="2026-07-08T00:00:00Z"),
+ ),
+ )
+
+ with self.capture_select_queries() as queries:
+ runner.calculate()
+
+ select_queries = _select_queries_without_metadata(queries)
+ self.assertEqual(len(select_queries), 2)
+ self.assertIn("__ai_events_fallback", select_queries[1])
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.py
index 42d173dd0f20..b47214c3f6e2 100644
--- a/posthog/taxonomy/taxonomy.py
+++ b/posthog/taxonomy/taxonomy.py
@@ -2466,8 +2466,8 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
},
"$ai_target_type": {
"label": "AI Target Type (LLM)",
- "description": "ID space of $ai_target_id. `generation_uuid` resolves against `events.uuid`; `trace_id` resolves against the `$ai_trace_id` property.",
- "examples": ["generation_uuid", "trace_id"],
+ "description": "ID space of $ai_target_id. `generation_uuid` resolves against `events.uuid`, `trace_id` resolves against the `$ai_trace_id` property, and `session_id` resolves against the `$ai_session_id` property.",
+ "examples": ["generation_uuid", "trace_id", "session_id"],
},
"$ai_metric_name": {
"label": "AI Metric Name (LLM)",
diff --git a/posthog/temporal/ai_observability/__init__.py b/posthog/temporal/ai_observability/__init__.py
index 1a1acadfbede..432ccc4cc6c9 100644
--- a/posthog/temporal/ai_observability/__init__.py
+++ b/posthog/temporal/ai_observability/__init__.py
@@ -44,9 +44,14 @@ from posthog.temporal.ai_observability.evaluation_workflow_activities import (
from posthog.temporal.ai_observability.metrics import EvalsMetricsInterceptor # noqa: F401
from posthog.temporal.ai_observability.run_aggregate_evaluation import (
RunAggregateEvaluationWorkflow,
+ check_session_settled_activity,
check_trace_settled_activity,
)
from posthog.temporal.ai_observability.run_evaluation import RunEvaluationWorkflow
+from posthog.temporal.ai_observability.run_session_evaluation import (
+ execute_session_hog_eval_activity,
+ execute_session_llm_judge_activity,
+)
from posthog.temporal.ai_observability.run_tagger import (
RunTaggerWorkflow,
disable_tagger_activity,
@@ -100,7 +105,10 @@ EVAL_ACTIVITIES = [
execute_sentiment_eval_activity,
execute_trace_llm_judge_activity,
execute_trace_hog_eval_activity,
+ execute_session_llm_judge_activity,
+ execute_session_hog_eval_activity,
check_trace_settled_activity,
+ check_session_settled_activity,
emit_evaluation_event_activity,
emit_trace_evaluation_event_activity,
emit_internal_telemetry_activity,
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.py
index 561359e762c8..14781ed1e546 100644
--- a/posthog/temporal/ai_observability/eval_reports/activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/activities.py
@@ -667,6 +667,7 @@ async def store_report_run_activity(
citations = content.get("citations", []) or []
all_referenced_ids = [c.get("generation_id", "") for c in citations if c.get("generation_id")]
all_referenced_trace_ids = [c.get("trace_id", "") for c in citations if c.get("trace_id")]
+ all_referenced_session_ids = [c.get("session_id", "") for c in citations if c.get("session_id")]
properties: dict = {
"$ai_evaluation_id": inputs.evaluation_id,
@@ -682,6 +683,7 @@ async def store_report_run_activity(
"$ai_report_citations": citations,
"$ai_report_referenced_generation_ids": all_referenced_ids,
"$ai_report_referenced_trace_ids": all_referenced_trace_ids,
+ "$ai_report_referenced_session_ids": all_referenced_session_ids,
"$ai_report_section_count": len(content.get("sections", [])),
}
if parsed_metrics is not None:
diff --git a/posthog/temporal/ai_observability/eval_reports/delivery.py b/posthog/temporal/ai_observability/eval_reports/delivery.py
index e5980c1ce8a5..f2ef29fbd8be 100644
--- a/posthog/temporal/ai_observability/eval_reports/delivery.py
+++ b/posthog/temporal/ai_observability/eval_reports/delivery.py
@@ -6,6 +6,7 @@ email HTML body and Slack Block Kit payloads from that shape.
"""
import re
+from dataclasses import dataclass
from datetime import UTC, datetime
from urllib.parse import quote, urlencode
@@ -45,10 +46,19 @@ _OUTCOME_LABELS = {
"sentiment": (("positive", "Positive"), ("neutral", "Neutral"), ("negative", "Negative")),
}
-type CitationMap = dict[str, tuple[str, str | None]]
+type CitationMap = dict[str, CitationLink]
_SAFE_CITATION_LABEL_RE = re.compile(r"^[A-Za-z0-9._~-]{1,8}$")
+@dataclass(frozen=True, kw_only=True)
+class CitationLink:
+ """Where a cited ID should take the reader, and what to call it if the ID doesn't render."""
+
+ trace_id: str
+ generation_id: str | None
+ session_id: str | None
+
+
def _inline_email_styles(html: str) -> str:
"""Add inline styles to HTML elements for email client compatibility."""
html = html.replace("<table>", f"<table {_EMAIL_TABLE_STYLE}>")
@@ -71,34 +81,48 @@ def _format_period_for_display(iso_str: str) -> str:
def _build_citation_map(citations: list[Citation]) -> CitationMap:
- """Map each cited ID to its trace and optional focused generation."""
+ """Map each cited ID to the unit the reader should land on."""
citation_map: CitationMap = {}
for citation in citations:
- if citation.generation_id and citation.trace_id:
- citation_map[citation.generation_id] = (citation.trace_id, citation.generation_id)
+ if citation.session_id:
+ citation_map[citation.session_id] = CitationLink(
+ trace_id=citation.trace_id, generation_id=None, session_id=citation.session_id
+ )
+ elif citation.generation_id and citation.trace_id:
+ citation_map[citation.generation_id] = CitationLink(
+ trace_id=citation.trace_id, generation_id=citation.generation_id, session_id=None
+ )
elif citation.trace_id:
- citation_map[citation.trace_id] = (citation.trace_id, None)
+ citation_map[citation.trace_id] = CitationLink(
+ trace_id=citation.trace_id, generation_id=None, session_id=None
+ )
return citation_map
-def _make_trace_link(project_id: int, trace_id: str, generation_id: str | None) -> str:
- """Build a trace URL, optionally focused on a cited generation."""
+def _make_citation_link(project_id: int, link: CitationLink) -> str:
+ """Build the URL for a cited unit: its session, or its trace optionally focused on a generation."""
from posthog.utils import absolute_uri
- # kea-router decodes the pathname once before matching, so preserve an encoded layer for the scene.
- encoded_trace_id = quote(quote(trace_id, safe=""), safe="")
+ # One encoded layer each, matching what the app's own URL builders emit: the session scene
+ # reads the ID straight off the decoded pathname, while the trace scene decodes once more.
+ if link.session_id:
+ return absolute_uri(f"/project/{project_id}/ai-observability/sessions/{quote(link.session_id, safe='')}")
+
+ encoded_trace_id = quote(quote(link.trace_id, safe=""), safe="")
path = f"/project/{project_id}/ai-observability/traces/{encoded_trace_id}"
- if generation_id:
- path = f"{path}?{urlencode({'event': generation_id})}"
+ if link.generation_id:
+ path = f"{path}?{urlencode({'event': link.generation_id})}"
return absolute_uri(path)
-def _citation_link_label(cited_id: str, generation_id: str | None) -> str:
+def _citation_link_label(cited_id: str, link: CitationLink) -> str:
"""Keep arbitrary IDs from breaking the generated Markdown link label."""
preview = cited_id[:8]
if _SAFE_CITATION_LABEL_RE.fullmatch(preview):
return f"{preview}..."
- return "generation" if generation_id else "trace"
+ if link.session_id:
+ return "session"
+ return "generation" if link.generation_id else "trace"
def _linkify_citations(text: str, project_id: int, citation_map: CitationMap) -> str:
@@ -120,19 +144,18 @@ def _linkify_citations(text: str, project_id: int, citation_map: CitationMap) ->
for i, cited_id in enumerate(citation_map):
placeholder = f"\x00CITE{i}\x00"
placeholders[placeholder] = cited_id
- _, generation_id = citation_map[cited_id]
for wrapper in [f"`` `{cited_id}` ``", f"`{cited_id}`", f"<{cited_id}>"]:
text = text.replace(wrapper, placeholder)
- if generation_id:
+ if citation_map[cited_id].generation_id:
text = text.replace(cited_id, placeholder)
# Phase 2: replace placeholders with markdown links.
for placeholder, cited_id in placeholders.items():
- trace_id, generation_id = citation_map[cited_id]
- link = _make_trace_link(project_id, trace_id, generation_id)
- label = _citation_link_label(cited_id, generation_id)
- text = text.replace(placeholder, f"[{label}]({link})")
+ link = citation_map[cited_id]
+ url = _make_citation_link(project_id, link)
+ label = _citation_link_label(cited_id, link)
+ text = text.replace(placeholder, f"[{label}]({url})")
return text
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
index 14bdf1ed526d..56ccc4e57742 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
@@ -29,7 +29,12 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (
_is_retriable_ch_error,
get_eval_report_tools,
)
-from posthog.temporal.ai_observability.eval_reports.targets import GENERATION_TARGET
+from posthog.temporal.ai_observability.eval_reports.targets import (
+ GENERATION_TARGET,
+ SESSION_ID_ALLOWLIST_KEY,
+ TRACE_ID_ALLOWLIST_KEY,
+ get_target_descriptor,
+)
from posthog.temporal.ai_observability.llm_endpoint import build_langchain_chat_client
logger = structlog.get_logger(__name__)
@@ -105,10 +110,11 @@ def _fallback_content(
went wrong at the agent level so the user isn't left staring at an empty UI.
"""
if metrics.total_runs == 0:
+ unit_label = get_target_descriptor(evaluation_target).unit_label
ingestion_hint = (
- "trace evaluation results are being ingested"
- if evaluation_target == "trace"
- else "`$ai_generation` events are being ingested"
+ "`$ai_generation` events are being ingested"
+ if evaluation_target == GENERATION_TARGET
+ else f"{unit_label} evaluation results are being ingested"
)
summary = (
f"No evaluation runs recorded for **{evaluation_name}** in this period. "
@@ -175,7 +181,7 @@ def _append_references_section(content: EvalReportContent) -> None:
"""
if not content.citations:
return
- refs_lines = [f"{i}. `{c.generation_id or c.trace_id}` — {c.reason}" for i, c in enumerate(content.citations, 1)]
+ refs_lines = [f"{i}. `{c.cited_id()}` — {c.reason}" for i, c in enumerate(content.citations, 1)]
content.sections.append(ReportSection(title="References", content="\n".join(refs_lines)))
@@ -292,7 +298,8 @@ def run_eval_report_agent(
"previous_period_start": previous_period_start,
"report_prompt_guidance": report_prompt_guidance,
"report": EvalReportContent(evaluation_target=evaluation_target, metrics=metrics),
- "trace_id_allowlist": [],
+ TRACE_ID_ALLOWLIST_KEY: [],
+ SESSION_ID_ALLOWLIST_KEY: [],
}
# Skip in gateway mode: the Go gateway captures $ai_generation itself, so the
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
index 7a63a5dff0ac..f69bea15f57d 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
@@ -2,6 +2,12 @@
from posthog.temporal.ai_observability.eval_reports.output_types import get_outcome_definition
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import MAX_REPORT_SECTIONS
+from posthog.temporal.ai_observability.eval_reports.targets import (
+ GENERATION_TARGET,
+ SESSION_TARGET,
+ TRACE_TARGET,
+ get_target_descriptor,
+)
EVAL_REPORT_SYSTEM_PROMPT = """You are an evaluation report agent for PostHog's AI observability platform. Your job is to analyze results from an LLM evaluation and produce a concise, grounded, example-backed report.
@@ -21,7 +27,7 @@ You build the report incrementally by calling three output tools:
1. **`set_title(title)`**: call exactly once. Write one specific, scannable headline that tells the reader the main finding at a glance.
2. **`add_section(title, content)`**: call 1 to {max_sections} times. The first section is the TL;DR. Prefer fewer substantive sections over filler.
-3. **`add_citation(generation_id, trace_id, reason)`**: {citation_tool_instruction}
+3. **`add_citation({citation_tool_signature})`**: {citation_tool_instruction}
## What not to do
@@ -116,7 +122,7 @@ def build_eval_report_system_prompt(
"last user message from real negative generations you cited.\n"
)
elif output_type == "boolean":
- evaluated_unit = "trace" if evaluation_target == "trace" else "generation"
+ evaluated_unit = get_target_descriptor(evaluation_target).unit_label
result_semantics = (
f"The evaluation returns a boolean. True means the {evaluated_unit} satisfied the configured criteria and false "
"means it did not. A fail is not inherently bad: always interpret pass and fail through the evaluation's "
@@ -139,10 +145,10 @@ def build_eval_report_system_prompt(
else:
raise ValueError(f"Unsupported evaluation report output type: {output_type}")
- if evaluation_target == "trace":
+ if evaluation_target == TRACE_TARGET:
+ citation_tool_signature = "trace_id, reason"
citation_tool_instruction = (
- "call for every trace you discuss, with an empty `generation_id`. "
- "Always call `sample_trace_details` first to verify the trace."
+ "call for every trace you discuss. Always call `sample_trace_details` first to verify the trace."
)
detail_tools_section = (
"- **`sample_trace_details(trace_ids)`**: canonical, bounded renderings for up to 10 traces. "
@@ -153,12 +159,36 @@ def build_eval_report_system_prompt(
1. Call `sample_eval_results({analysis_sample_arguments})` to find candidate trace IDs. Sample `{primary_outcome}` as contrast when useful.
2. Call `sample_trace_details(trace_ids)` to inspect the actual traces.
-3. Call `add_citation(generation_id=\"\", trace_id=trace_id, reason=reason)` for each example you use.
+3. Call `add_citation(trace_id=trace_id, reason=reason)` for each example you use.
4. Reference the trace ID inline with single backticks so the renderer can link it.
If a trace cannot be resolved, try another example. If none resolve, report the data-quality limitation."""
detail_step = "Call `sample_trace_details(...)` on 3-5 useful examples."
- elif evaluation_target == "generation":
+ elif evaluation_target == SESSION_TARGET:
+ citation_tool_signature = "session_id, reason"
+ citation_tool_instruction = (
+ "call for every session you discuss. Always call `sample_session_details` first to verify the "
+ "session. Add `trace_id` when one specific trace inside the session carries the finding."
+ )
+ detail_tools_section = (
+ "- **`sample_session_details(session_ids)`**: the trace map for up to 5 sessions, with per-trace "
+ "event and generation counts and timestamps. Call this before citing.\n"
+ "- **`get_session_detail(session_id)`**: the full trace map for one session, up to 50 traces.\n"
+ "- **`get_trace_detail(trace_id)`**: the canonical rendering of one trace from a session you mapped."
+ )
+ grounding_rule = f"""A session is a bag of traces, so reading one is two steps: map it, then open the traces that matter. For every recurring outcome pattern or quality issue you describe:
+
+1. Call `sample_eval_results({analysis_sample_arguments})` to find candidate session IDs. Sample `{primary_outcome}` as contrast when useful.
+2. Call `sample_session_details(session_ids)` to see how those sessions are shaped, then `get_trace_detail(trace_id)` to read the traces that look relevant. Look at how the session progressed across traces, not just at one turn.
+3. Call `add_citation(session_id=session_id, reason=reason)` for each example you use.
+4. Reference the session ID inline with single backticks so the renderer can link it.
+
+If a session cannot be resolved, try another example. If none resolve, report the data-quality limitation."""
+ detail_step = (
+ "Call `sample_session_details(...)` on 3-5 useful examples, then read the traces that look relevant."
+ )
+ elif evaluation_target == GENERATION_TARGET:
+ citation_tool_signature = "generation_id, trace_id, reason"
citation_tool_instruction = (
"call for every example you discuss. Always call `sample_generation_details` first to verify the "
"generation and get its `trace_id`."
@@ -174,7 +204,7 @@ If a trace cannot be resolved, try another example. If none resolve, report the
1. Call `sample_eval_results({analysis_sample_arguments})` to find candidate generation IDs. Sample `{primary_outcome}` as contrast when useful.
2. Call `sample_generation_details(generation_ids)` to inspect the actual input and output and obtain each trace ID.
-3. Call `add_citation(generation_id, trace_id, reason)` for each example you use.
+3. Call `add_citation(generation_id=generation_id, trace_id=trace_id, reason=reason)` for each example you use.
4. Reference the generation ID inline with single backticks so the renderer can link it.
If a generation cannot be resolved, try another example. If none resolve, report the data-quality limitation."""
@@ -201,6 +231,7 @@ If a generation cannot be resolved, try another example. If none resolve, report
sample_ordering_signature=sample_ordering_signature,
sample_ordering_instruction=sample_ordering_instruction,
outcome_analysis_step=outcome_analysis_step,
+ citation_tool_signature=citation_tool_signature,
citation_tool_instruction=citation_tool_instruction,
detail_tools_section=detail_tools_section,
grounding_rule=grounding_rule,
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py b/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
index 34a4dfed9d57..40090eecc29b 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
@@ -1,12 +1,12 @@
"""Dataclasses for evaluation report content, metrics, and citations.
The v2 schema splits the report into:
-- `evaluation_target`: the evaluated unit (`generation` or `trace`)
+- `evaluation_target`: the evaluated unit (`generation`, `trace`, or `session`)
- `metrics`: structured numeric data computed mechanically from ClickHouse,
the agent cannot fabricate these
- `title`: the agent's punchline headline (required, one line)
- `sections`: 1-6 agent-chosen titled markdown sections
-- `citations`: structured target references (generation_id + trace_id + reason)
+- `citations`: structured target references (generation_id + trace_id + session_id + reason)
This separation lets downstream consumers (signals, inbox, coding agents) query
`metrics` and `citations` without parsing prose, and lets the agent focus on
@@ -81,21 +81,33 @@ def calculate_boolean_pass_rate(counts: dict[str, int], *, empty_as_none: bool =
class Citation:
"""An inspected example cited by the agent to ground a specific finding.
- Generation reports store both IDs so viewers can link to the generation
- without a runtime lookup. Trace reports leave `generation_id` empty and use
- `trace_id` as the reference. `reason` is a short free-form category for why
- the example is interesting.
+ Every citation carries the ID of the unit that was evaluated, plus whatever
+ narrower IDs the agent verified along the way, so a viewer can link straight
+ to it without a runtime lookup. Generation reports fill `generation_id` and
+ `trace_id`; trace reports fill `trace_id`; session reports fill `session_id`
+ and optionally the `trace_id` the agent read inside it. `reason` is a short
+ free-form category for why the example is interesting.
"""
- generation_id: str
- trace_id: str
- reason: str
+ generation_id: str = ""
+ trace_id: str = ""
+ reason: str = ""
+ session_id: str = ""
+
+ def cited_id(self) -> str:
+ """The ID of the evaluated unit — what the report text refers to and links to.
+
+ Only a session citation carries `session_id` and only a generation citation carries
+ `generation_id`, so this resolves to the right ID without knowing the target.
+ """
+ return self.session_id or self.generation_id or self.trace_id
def to_dict(self) -> dict:
return {
"generation_id": self.generation_id,
"trace_id": self.trace_id,
"reason": self.reason,
+ "session_id": self.session_id,
}
@staticmethod
@@ -104,6 +116,7 @@ class Citation:
generation_id=data.get("generation_id", ""),
trace_id=data.get("trace_id", ""),
reason=data.get("reason", ""),
+ session_id=data.get("session_id", ""),
)
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/state.py b/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
index 3949187ee9af..4b661f6bef42 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
@@ -35,6 +35,10 @@ class EvalReportAgentState(TypedDict):
previous_period_start: str
report_prompt_guidance: str
- # Working state — the agent builds this up via tool calls
+ # Working state — the agent builds this up via tool calls.
+ # The allowlists gate the detail tools: an ID only becomes inspectable once a query
+ # returned it. Session reports fill both — sessions from evaluation results, traces
+ # from the sessions the agent maps.
report: EvalReportContent
trace_id_allowlist: list[str]
+ session_id_allowlist: list[str]
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
index 121419f7118f..117cd00baf22 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
@@ -75,15 +75,36 @@ class TestSystemPromptFormat(SimpleTestCase):
self.assertIn("get_top_outcome_reasons", formatted)
self.assertIn("Inspect grouped reasons", formatted)
- def test_trace_prompt_uses_only_trace_detail_workflow(self):
- formatted = self._build_prompt(evaluation_target="trace")
-
- self.assertIn("Evaluation target: trace", formatted)
- self.assertIn("sample_trace_details", formatted)
- self.assertIn("get_trace_detail", formatted)
- self.assertIn('generation_id=""', formatted)
- self.assertNotIn("sample_generation_details", formatted)
- self.assertIn("trace satisfied the configured criteria", formatted)
+ # A prompt that names another target's detail tools sends the agent after IDs its
+ # allowlist will reject, so every target's prompt has to describe only its own workflow.
+ @parameterized.expand(
+ [
+ (
+ "trace",
+ ["sample_trace_details", "get_trace_detail", "add_citation(trace_id=trace_id"],
+ ["sample_generation_details", "sample_session_details"],
+ ),
+ (
+ "generation",
+ ["sample_generation_details", "get_generation_detail", "add_citation(generation_id=generation_id"],
+ ["sample_trace_details", "sample_session_details"],
+ ),
+ (
+ "session",
+ ["sample_session_details", "get_session_detail", "add_citation(session_id=session_id"],
+ ["sample_generation_details", "sample_trace_details"],
+ ),
+ ]
+ )
+ def test_prompt_describes_only_its_own_target_workflow(self, target, expected, unexpected):
+ formatted = self._build_prompt(evaluation_target=target)
+
+ self.assertIn(f"Evaluation target: {target}", formatted)
+ self.assertIn(f"{target} satisfied the configured criteria", formatted)
+ for fragment in expected:
+ self.assertIn(fragment, formatted)
+ for fragment in unexpected:
+ self.assertNotIn(fragment, formatted)
class TestComputeMetrics(SimpleTestCase):
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py
index 309a26bab20f..d6610745b1a7 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py
@@ -2,6 +2,8 @@
from django.test import SimpleTestCase
+from parameterized import parameterized
+
from posthog.temporal.ai_observability.eval_reports.output_types import SUPPORTED_EVAL_REPORT_OUTPUT_TYPES
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
MAX_REPORT_SECTIONS,
@@ -26,7 +28,7 @@ class TestCitation(SimpleTestCase):
c = Citation(generation_id="a-gen-id", trace_id="a-trace-id", reason="high_cost")
self.assertEqual(
c.to_dict(),
- {"generation_id": "a-gen-id", "trace_id": "a-trace-id", "reason": "high_cost"},
+ {"generation_id": "a-gen-id", "trace_id": "a-trace-id", "reason": "high_cost", "session_id": ""},
)
def test_from_dict(self):
@@ -34,15 +36,35 @@ class TestCitation(SimpleTestCase):
self.assertEqual(c.generation_id, "g")
self.assertEqual(c.trace_id, "t")
self.assertEqual(c.reason, "refusal")
+ self.assertEqual(c.session_id, "")
def test_from_dict_missing_fields(self):
c = Citation.from_dict({})
self.assertEqual(c.generation_id, "")
self.assertEqual(c.trace_id, "")
self.assertEqual(c.reason, "")
-
- def test_roundtrip(self):
- original = Citation(generation_id="g1", trace_id="t1", reason="some reason")
+ self.assertEqual(c.session_id, "")
+
+ @parameterized.expand(
+ [
+ ("generation", Citation(generation_id="g1", trace_id="t1", reason="r"), "g1"),
+ ("trace", Citation(trace_id="t1", reason="r"), "t1"),
+ # A session citation may name the trace the agent read inside it, but the report
+ # text and its link are about the session, so that is the ID it resolves to.
+ ("session", Citation(session_id="s1", trace_id="t1", reason="r"), "s1"),
+ ]
+ )
+ def test_cited_id_is_the_evaluated_unit(self, _name, citation, expected):
+ self.assertEqual(citation.cited_id(), expected)
+
+ @parameterized.expand(
+ [
+ ("generation", Citation(generation_id="g1", trace_id="t1", reason="some reason")),
+ ("trace", Citation(trace_id="t1", reason="some reason")),
+ ("session", Citation(session_id="s1", trace_id="t1", reason="some reason")),
+ ]
+ )
+ def test_roundtrip(self, _name, original):
self.assertEqual(Citation.from_dict(original.to_dict()), original)
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
index 6847e273429d..0163b397cc17 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
@@ -17,6 +17,8 @@ from django.utils import timezone
from clickhouse_driver.errors import NetworkError, SocketTimeoutError
from parameterized import parameterized
+from posthog.hogql import ast
+
from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
MAX_REPORT_SECTIONS,
@@ -25,6 +27,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
ReportSection,
)
from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (
+ _SESSION_TRACES_SQL,
_UUID_RE,
_ch_ts,
_execute_ch_query_with_retry,
@@ -34,17 +37,20 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (
add_section,
get_eval_report_tools,
get_report_run,
+ get_session_detail,
get_summary_metrics,
get_trace_detail,
list_all_eval_results,
list_recent_report_runs,
sample_eval_results,
+ sample_session_details,
sample_trace_details,
set_title,
)
_VALID_GEN_ID = "12345678-1234-1234-1234-123456789abc"
_VALID_TRACE_ID = "abcdefab-cdef-abcd-efab-cdefabcdefab"
+_VALID_SESSION_ID = "fedcbafe-dcba-fedc-bafe-dcbafedcbafe"
# LangChain @tool returns StructuredTool which has .func, but mypy types it as BaseTool
_set_title_fn = set_title.func # type: ignore[attr-defined]
@@ -57,6 +63,8 @@ _list_all_eval_results_fn = list_all_eval_results.func # type: ignore[attr-defi
_sample_eval_results_fn = sample_eval_results.func # type: ignore[attr-defined]
_sample_trace_details_fn = sample_trace_details.func # type: ignore[attr-defined]
_get_trace_detail_fn = get_trace_detail.func # type: ignore[attr-defined]
+_sample_session_details_fn = sample_session_details.func # type: ignore[attr-defined]
+_get_session_detail_fn = get_session_detail.func # type: ignore[attr-defined]
def _per_query_memory_limit_error() -> ClickHouseQueryMemoryLimitExceeded:
@@ -68,6 +76,7 @@ def _per_query_memory_limit_error() -> ClickHouseQueryMemoryLimitExceeded:
class _ReportToolState(TypedDict):
report: EvalReportContent
trace_id_allowlist: list[str]
+ session_id_allowlist: list[str]
evaluation_target: NotRequired[str]
team_id: NotRequired[int]
evaluation_id: NotRequired[str]
@@ -77,17 +86,22 @@ class _ReportToolState(TypedDict):
def _state_with_empty_report(*, evaluation_target: str | None = None) -> _ReportToolState:
- state: _ReportToolState = {"report": EvalReportContent(), "trace_id_allowlist": []}
+ state: _ReportToolState = {
+ "report": EvalReportContent(),
+ "trace_id_allowlist": [],
+ "session_id_allowlist": [],
+ }
if evaluation_target is not None:
state["evaluation_target"] = evaluation_target
return state
-def _trace_report_tool_state() -> _ReportToolState:
+def _aggregate_report_tool_state(evaluation_target: str = "trace") -> _ReportToolState:
return {
"report": EvalReportContent(),
"trace_id_allowlist": [],
- "evaluation_target": "trace",
+ "session_id_allowlist": [],
+ "evaluation_target": evaluation_target,
"team_id": 7,
"evaluation_id": "eval-id",
"output_type": "boolean",
@@ -96,6 +110,10 @@ def _trace_report_tool_state() -> _ReportToolState:
}
+def _trace_report_tool_state() -> _ReportToolState:
+ return _aggregate_report_tool_state("trace")
+
+
class TestChTs(SimpleTestCase):
@parameterized.expand(
[
@@ -394,6 +412,7 @@ class TestTraceDetailTools(SimpleTestCase):
def test_target_and_output_specific_tool_sets_do_not_expose_irrelevant_tools(self):
generation_tools = {tool.name for tool in get_eval_report_tools("generation", "boolean")}
trace_tools = {tool.name for tool in get_eval_report_tools("trace", "boolean")}
+ session_tools = {tool.name for tool in get_eval_report_tools("session", "boolean")}
sentiment_tools = {tool.name for tool in get_eval_report_tools("generation", "sentiment")}
self.assertIn("sample_generation_details", generation_tools)
@@ -401,10 +420,105 @@ class TestTraceDetailTools(SimpleTestCase):
self.assertIn("sample_trace_details", trace_tools)
self.assertIn("get_trace_detail", trace_tools)
self.assertNotIn("sample_generation_details", trace_tools)
+ self.assertIn("sample_session_details", session_tools)
+ self.assertIn("get_session_detail", session_tools)
+ # A session is read through its traces, so the trace deep-dive comes along.
+ self.assertIn("get_trace_detail", session_tools)
+ self.assertNotIn("sample_generation_details", session_tools)
+ self.assertNotIn("sample_session_details", trace_tools)
self.assertIn("get_top_outcome_reasons", generation_tools)
self.assertNotIn("get_top_outcome_reasons", sentiment_tools)
+class TestSessionTracesQueryFallback(SimpleTestCase):
+ def test_placeholder_names_survive_the_events_table_rewrite(self) -> None:
+ """The rewriter descends into placeholders, so a placeholder named after an ai_events
+ column is rewritten into a column reference and substitution then fails — which only
+ shows up on the events fallback, the path every other session test mocks out."""
+ from posthog.hogql.parser import parse_select
+ from posthog.hogql.visitor import TraversingVisitor
+
+ from posthog.hogql_queries.ai.ai_column_rewriter import rewrite_query_for_events_table
+
+ names: list[str] = []
+
+ class _CollectPlaceholders(TraversingVisitor):
+ def visit_placeholder(self, node: ast.Placeholder) -> None:
+ assert isinstance(node.expr, ast.Field)
+ names.append(".".join(str(part) for part in node.expr.chain))
+
+ _CollectPlaceholders().visit(rewrite_query_for_events_table(parse_select(_SESSION_TRACES_SQL)))
+
+ self.assertEqual(sorted(names), ["limit", "target_session_id", "ts_end", "ts_start"])
+
+
+class TestSessionDetailTools(SimpleTestCase):
+ def _state(self) -> _ReportToolState:
+ return _aggregate_report_tool_state("session")
+
+ def _allowlisted_state(
+ self, mock_execute_hogql: MagicMock, session_id: str = _VALID_SESSION_ID
+ ) -> _ReportToolState:
+ state = self._state()
+ mock_execute_hogql.return_value = [[session_id, True, "matched", True, None]]
+ _sample_eval_results_fn(state=state)
+ mock_execute_hogql.reset_mock()
+ return state
+
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")
+ def test_evaluation_results_fill_the_session_allowlist_not_the_trace_one(
+ self, mock_execute_hogql: MagicMock
+ ) -> None:
+ state = self._allowlisted_state(mock_execute_hogql, "customer/session:42")
+
+ self.assertEqual(state["session_id_allowlist"], ["customer/session:42"])
+ self.assertEqual(state["trace_id_allowlist"], [])
+
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql_via_ai_events")
+ def test_detail_rejects_session_no_evaluation_query_returned(self, mock_ai_events: MagicMock) -> None:
+ result = json.loads(_get_session_detail_fn(state=self._state(), session_id=_VALID_SESSION_ID))
+
+ self.assertIn("not available", result["error"])
+ mock_ai_events.assert_not_called()
+
+ @patch("posthog.models.Team.objects.get")
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql_via_ai_events")
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")
+ def test_detail_maps_traces_and_unlocks_them_for_the_trace_tools(
+ self, mock_execute_hogql: MagicMock, mock_ai_events: MagicMock, _mock_get_team: MagicMock
+ ) -> None:
+ state = self._allowlisted_state(mock_execute_hogql)
+ started = dt.datetime(2026, 4, 8, 14, 0, tzinfo=dt.UTC)
+ mock_ai_events.return_value = [
+ ["trace-a", 12, 4, started, started],
+ ["trace-b", 3, 1, started, started],
+ ]
+
+ result = json.loads(_get_session_detail_fn(state=state, session_id=_VALID_SESSION_ID))
+
+ self.assertEqual([trace["trace_id"] for trace in result["traces"]], ["trace-a", "trace-b"])
+ self.assertEqual(result["trace_count"], 2)
+ self.assertEqual(result["event_count"], 15)
+ self.assertNotIn("truncated", result)
+ # Without this the agent could map a session and then be refused every trace inside it.
+ self.assertEqual(state["trace_id_allowlist"], ["trace-a", "trace-b"])
+
+ @patch("posthog.models.Team.objects.get")
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql_via_ai_events")
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")
+ def test_sample_bounds_the_trace_list_and_says_so(
+ self, mock_execute_hogql: MagicMock, mock_ai_events: MagicMock, _mock_get_team: MagicMock
+ ) -> None:
+ state = self._allowlisted_state(mock_execute_hogql)
+ started = dt.datetime(2026, 4, 8, 14, 0, tzinfo=dt.UTC)
+ mock_ai_events.return_value = [[f"trace-{index}", 1, 1, started, started] for index in range(20)]
+
+ result = json.loads(_sample_session_details_fn(state=state, session_ids=[_VALID_SESSION_ID]))
+
+ self.assertEqual(len(result[0]["traces"]), 10)
+ self.assertIn("first 10 traces", result[0]["truncated"])
+
+
class TestUuidRegex(SimpleTestCase):
def test_matches_canonical_uuid(self):
self.assertIsNotNone(_UUID_RE.fullmatch("12345678-1234-1234-1234-123456789abc"))
@@ -625,6 +739,72 @@ class TestAddCitation(SimpleTestCase):
self.assertEqual(state["report"].citations[1].reason, "second")
+class TestSessionCitations(SimpleTestCase):
+ def _allowlisted_state(self) -> _ReportToolState:
+ state = _aggregate_report_tool_state("session")
+ state["session_id_allowlist"].append(_VALID_SESSION_ID)
+ state["trace_id_allowlist"].append("trace-in-session")
+ return state
+
+ def test_cites_the_session_alone(self):
+ state = self._allowlisted_state()
+
+ result = _add_citation_fn(state=state, session_id=_VALID_SESSION_ID, reason="abandoned midway")
+
+ self.assertNotIn("Error", result)
+ self.assertEqual(
+ state["report"].citations[0],
+ Citation(session_id=_VALID_SESSION_ID, reason="abandoned midway"),
+ )
+
+ def test_cites_a_trace_inside_the_session_for_extra_precision(self):
+ state = self._allowlisted_state()
+
+ result = _add_citation_fn(
+ state=state, session_id=_VALID_SESSION_ID, trace_id="trace-in-session", reason="the failing turn"
+ )
+
+ self.assertNotIn("Error", result)
+ self.assertEqual(state["report"].citations[0].trace_id, "trace-in-session")
+ # The report is about the session, so that is what the text refers to and links to.
+ self.assertEqual(state["report"].citations[0].cited_id(), _VALID_SESSION_ID)
+
+ @parameterized.expand(
+ [
+ # Each of these would put an ID in the report that the agent never verified, or one
+ # from a different ID space than the report's own — a broken or wrong link either way.
+ ("session never returned by a query", {"session_id": "fabricated-session"}),
+ ("trace from outside the mapped session", {"session_id": _VALID_SESSION_ID, "trace_id": "other-trace"}),
+ ("no session at all", {"trace_id": "trace-in-session"}),
+ ("a generation ID on a session report", {"session_id": _VALID_SESSION_ID, "generation_id": _VALID_GEN_ID}),
+ ("a control character in the session ID", {"session_id": "session\nid"}),
+ ]
+ )
+ def test_refuses_citation(self, _name, kwargs):
+ state = self._allowlisted_state()
+
+ result = _add_citation_fn(state=state, reason="r", **kwargs)
+
+ self.assertIn("Error", result)
+ self.assertEqual(state["report"].citations, [])
+
+ @parameterized.expand([("generation",), ("trace",)])
+ def test_other_targets_refuse_a_session_id(self, evaluation_target):
+ state = _state_with_empty_report(evaluation_target=evaluation_target)
+ state["trace_id_allowlist"].append(_VALID_TRACE_ID)
+
+ result = _add_citation_fn(
+ state=state,
+ generation_id=_VALID_GEN_ID if evaluation_target == "generation" else "",
+ trace_id=_VALID_TRACE_ID,
+ session_id=_VALID_SESSION_ID,
+ reason="r",
+ )
+
+ self.assertIn("Error", result)
+ self.assertEqual(state["report"].citations, [])
+
+
class TestListAndGetReportRun(BaseTest):
"""DB-backed tests for the split list_recent_report_runs + get_report_run tools."""
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
index 79eb6fb18f96..317743a7958b 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
@@ -42,7 +42,11 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
)
from posthog.temporal.ai_observability.eval_reports.targets import (
GENERATION_TARGET,
+ SESSION_ID_ALLOWLIST_KEY,
+ SESSION_TARGET,
+ TRACE_ID_ALLOWLIST_KEY,
TRACE_TARGET,
+ get_target_descriptor,
resolve_evaluation_target,
target_event_predicate,
)
@@ -62,52 +66,59 @@ logger = structlog.get_logger(__name__)
_UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
_TARGET_ID_EXPRESSION = "coalesce(nullIf(properties.$ai_target_id, ''), properties.$ai_target_event_id)"
-_MAX_TRACE_ID_LENGTH = 255
+_MAX_OPAQUE_ID_LENGTH = 255
_MAX_TRACE_SAMPLE_IDS = 10
_MAX_TRACE_SAMPLE_CHARS = 3_000
_MAX_TRACE_DETAIL_CHARS = 12_000
def _target_id_key(state: dict) -> str:
- return "trace_id" if resolve_evaluation_target(state.get("evaluation_target")) == TRACE_TARGET else "generation_id"
+ return get_target_descriptor(state.get("evaluation_target")).id_key
-def _normalize_trace_id(trace_id: object) -> str | None:
- """Validate an opaque trace ID without assuming it is a UUID."""
- if not isinstance(trace_id, str):
+def _normalize_opaque_id(value: object) -> str | None:
+ """Validate an opaque trace or session ID without assuming it is a UUID."""
+ if not isinstance(value, str):
return None
- if not trace_id.strip() or len(trace_id) > _MAX_TRACE_ID_LENGTH:
+ if not value.strip() or len(value) > _MAX_OPAQUE_ID_LENGTH:
return None
- if any(ord(character) < 32 or ord(character) == 127 for character in trace_id):
+ if any(ord(character) < 32 or ord(character) == 127 for character in value):
return None
- return trace_id
+ return value
-def _remember_returned_trace_ids(state: dict, target_ids: list[object]) -> None:
- if resolve_evaluation_target(state.get("evaluation_target")) != TRACE_TARGET:
+def _remember_ids(state: dict, allowlist_key: str | None, ids: list[object]) -> None:
+ """Record IDs a query returned so detail tools can later accept them."""
+ if allowlist_key is None:
return
- allowlist = state.get("trace_id_allowlist")
+ allowlist = state.get(allowlist_key)
if not isinstance(allowlist, list):
return
- known_trace_ids = set(allowlist)
- for target_id in target_ids:
- trace_id = _normalize_trace_id(target_id)
- if trace_id is not None and trace_id not in known_trace_ids:
- allowlist.append(trace_id)
- known_trace_ids.add(trace_id)
+ known_ids = set(allowlist)
+ for candidate in ids:
+ normalized = _normalize_opaque_id(candidate)
+ if normalized is not None and normalized not in known_ids:
+ allowlist.append(normalized)
+ known_ids.add(normalized)
-def _is_returned_trace_id(state: dict, trace_id: str) -> bool:
- allowlist = state.get("trace_id_allowlist")
- return isinstance(allowlist, list) and trace_id in allowlist
+def _remember_returned_target_ids(state: dict, target_ids: list[object]) -> None:
+ _remember_ids(state, get_target_descriptor(state.get("evaluation_target")).allowlist_key, target_ids)
+
+
+def _is_allowlisted(state: dict, allowlist_key: str, value: str) -> bool:
+ allowlist = state.get(allowlist_key)
+ return isinstance(allowlist, list) and value in allowlist
def _report_run_target_filter(evaluation_target: str) -> Q:
- if resolve_evaluation_target(evaluation_target) == TRACE_TARGET:
- return Q(content__evaluation_target=TRACE_TARGET)
- return Q(content__evaluation_target=GENERATION_TARGET) | Q(content__evaluation_target__isnull=True)
+ target = resolve_evaluation_target(evaluation_target)
+ if target == GENERATION_TARGET:
+ # Generation reports predate the field, so rows written before it existed are theirs.
+ return Q(content__evaluation_target=GENERATION_TARGET) | Q(content__evaluation_target__isnull=True)
+ return Q(content__evaluation_target=target)
def _completed_report_run_filter() -> Q:
@@ -282,10 +293,11 @@ def _execute_hogql(team_id: int, query_str: str, placeholders: dict | None = Non
def _execute_hogql_via_ai_events(team: "Team", query_str: str, placeholders: dict | None = None) -> list[list]:
"""Execute a HogQL query written against `posthog.ai_events` with the events-table fallback.
- Use this only for queries that read heavy columns (`input`, `output`,
- `output_choices`, `input_state`, `output_state`, `tools`) — those live only
- on the dedicated `ai_events` table, not in `events.properties`. Other queries
- should keep using `_execute_hogql` against `events`.
+ Use this for queries that read heavy columns (`input`, `output`, `output_choices`,
+ `input_state`, `output_state`, `tools`), which live only on the dedicated `ai_events`
+ table and not in `events.properties`, or that filter on a column `ai_events` indexes
+ and `events` does not (`session_id` carries a bloom filter). Everything else should
+ keep using `_execute_hogql` against `events`.
"""
from posthog.hogql.parser import parse_select
@@ -526,7 +538,7 @@ def list_all_eval_results(
""",
placeholders=shared_placeholders,
)
- _remember_returned_trace_ids(state, [row[0] for row in rows if row])
+ _remember_returned_target_ids(state, [row[0] for row in rows if row])
max_reasoning_length = min(max(20, max_reasoning_length), 200)
lines = []
@@ -613,7 +625,7 @@ def sample_eval_results(
"limit": ast.Constant(value=limit),
},
)
- _remember_returned_trace_ids(state, [row[0] for row in rows if row])
+ _remember_returned_target_ids(state, [row[0] for row in rows if row])
target_id_key = _target_id_key(state)
result = []
@@ -992,11 +1004,11 @@ def get_generation_text_repr(
def _fetch_trace_detail(state: dict, trace_id: object, max_length: int) -> dict:
- normalized_trace_id = _normalize_trace_id(trace_id)
+ normalized_trace_id = _normalize_opaque_id(trace_id)
if normalized_trace_id is None:
return {"error": "Invalid trace ID"}
- if not _is_returned_trace_id(state, normalized_trace_id):
+ if not _is_allowlisted(state, TRACE_ID_ALLOWLIST_KEY, normalized_trace_id):
return {
"trace_id": normalized_trace_id,
"error": "Trace ID is not available for this evaluation report",
@@ -1054,7 +1066,7 @@ def sample_trace_details(
details: list[dict] = []
seen: set[str] = set()
for trace_id in trace_ids[:_MAX_TRACE_SAMPLE_IDS]:
- normalized_trace_id = _normalize_trace_id(trace_id)
+ normalized_trace_id = _normalize_opaque_id(trace_id)
if normalized_trace_id is None:
details.append({"error": "Invalid trace ID"})
continue
@@ -1081,6 +1093,161 @@ def get_trace_detail(
return json.dumps(_fetch_trace_detail(state, trace_id, _MAX_TRACE_DETAIL_CHARS), indent=2)
+_MAX_SESSION_SAMPLE_IDS = 5
+_MAX_SESSION_SAMPLE_TRACES = 10
+_MAX_SESSION_DETAIL_TRACES = 50
+# A session's own events can start long before the evaluation that graded it, and the report period
+# only locates evaluation events, so `_widened_ts_window`'s 7-day backoff for evaluation lag is
+# nowhere near enough to cover a long session's head. `session_id` carries a bloom filter, so the
+# extra width is cheap.
+#
+# This widens up to the ai_events retention, not past it. A session still running after its oldest
+# events aged out of ai_events keeps its head clipped: `query_ai_events` only falls back to the
+# shared events table when the primary returns zero rows, and a session with any recent trace
+# returns some. Those traces are then absent from the map and unciteable. Reaching them would mean
+# querying `events` for session structure, which has no session_id index — not worth it for a
+# background report, but the limit is real rather than solved here.
+_SESSION_EXTRA_LOOKBACK_DAYS = 30
+
+# The placeholder is deliberately not named `session_id`: on the events fallback the column
+# rewriter descends into placeholders and would rewrite `{session_id}` into
+# `{properties.$ai_session_id}`, which then has no matching key and fails substitution.
+_SESSION_TRACES_SQL = """
+SELECT
+ trace_id,
+ count() AS event_count,
+ countIf(event = '$ai_generation') AS generation_count,
+ min(timestamp) AS first_seen,
+ max(timestamp) AS last_seen
+FROM posthog.ai_events AS ai_events
+WHERE session_id = {target_session_id}
+ AND isNotNull(trace_id)
+ AND trace_id != ''
+ AND timestamp >= {ts_start}
+ AND timestamp <= {ts_end}
+GROUP BY trace_id
+ORDER BY first_seen
+LIMIT {limit}
+"""
+
+
+def _fetch_session_detail(state: dict, session_id: object, max_traces: int) -> dict:
+ """Summarize one session as its ordered traces, and unlock those traces for inspection.
+
+ Returns structure rather than content on purpose: a session's full transcript is far
+ larger than the trace renderings the agent already has tools for, so this hands back a
+ map and lets the agent spend its context on the traces that look worth reading.
+ """
+ from posthog.models import Team
+
+ normalized_session_id = _normalize_opaque_id(session_id)
+ if normalized_session_id is None:
+ return {"error": "Invalid session ID"}
+
+ if not _is_allowlisted(state, SESSION_ID_ALLOWLIST_KEY, normalized_session_id):
+ return {
+ "session_id": normalized_session_id,
+ "error": "Session ID is not available for this evaluation report",
+ }
+
+ widened_start, widened_end = _widened_ts_window(state)
+ ts_start = widened_start - timedelta(days=_SESSION_EXTRA_LOOKBACK_DAYS)
+
+ try:
+ team = Team.objects.get(id=state["team_id"])
+ rows = _execute_hogql_via_ai_events(
+ team,
+ _SESSION_TRACES_SQL,
+ placeholders={
+ "target_session_id": ast.Constant(value=normalized_session_id),
+ "ts_start": ast.Constant(value=ts_start),
+ "ts_end": ast.Constant(value=widened_end),
+ "limit": ast.Constant(value=max_traces + 1),
+ },
+ )
+ except Exception as error:
+ logger.exception(
+ "llma_eval_reports_session_detail_failed",
+ session_id=normalized_session_id,
+ team_id=state["team_id"],
+ error_type=type(error).__name__,
+ )
+ return {"session_id": normalized_session_id, "error": "Session could not be inspected"}
+
+ if not rows:
+ return {"session_id": normalized_session_id, "error": "Session not found"}
+
+ truncated = len(rows) > max_traces
+ rows = rows[:max_traces]
+ # The agent may only open traces this session actually contains, so record them before returning.
+ _remember_ids(state, TRACE_ID_ALLOWLIST_KEY, [row[0] for row in rows])
+
+ traces = [
+ {
+ "trace_id": str(row[0]),
+ "event_count": int(row[1] or 0),
+ "generation_count": int(row[2] or 0),
+ "first_seen": str(row[3]),
+ "last_seen": str(row[4]),
+ }
+ for row in rows
+ ]
+ detail: dict = {
+ "session_id": normalized_session_id,
+ "trace_count": len(traces),
+ "event_count": sum(trace["event_count"] for trace in traces),
+ "traces": traces,
+ }
+ if truncated:
+ detail["truncated"] = f"Showing the first {max_traces} traces of this session, ordered by start time."
+ return detail
+
+
+@tool
+def sample_session_details(
+ state: Annotated[dict, InjectedState],
+ session_ids: list[str],
+) -> str:
+ """Inspect the shape of a small set of session evaluation targets.
+
+ Each session is summarized as its ordered traces, with event and generation counts
+ and timestamps. At most 5 sessions and 10 traces per session are returned. Session
+ IDs are opaque strings and do not need to be UUIDs. Call `get_session_detail` for
+ a fuller trace list, and `get_trace_detail` to read a specific trace.
+
+ Args:
+ session_ids: Session IDs returned by sample_eval_results (max 5)
+ """
+ details: list[dict] = []
+ seen: set[str] = set()
+ for session_id in session_ids[:_MAX_SESSION_SAMPLE_IDS]:
+ normalized_session_id = _normalize_opaque_id(session_id)
+ if normalized_session_id is None:
+ details.append({"error": "Invalid session ID"})
+ continue
+ if normalized_session_id in seen:
+ continue
+ seen.add(normalized_session_id)
+ details.append(_fetch_session_detail(state, normalized_session_id, _MAX_SESSION_SAMPLE_TRACES))
+ return json.dumps(details, indent=2)
+
+
+@tool
+def get_session_detail(
+ state: Annotated[dict, InjectedState],
+ session_id: str,
+) -> str:
+ """Map one session in full: every trace it contains, in order, up to 50.
+
+ Use this to understand how a session unfolded, then call `get_trace_detail(trace_id)`
+ on the traces that look relevant to read what actually happened inside them.
+
+ Args:
+ session_id: Session ID returned by sample_eval_results
+ """
+ return json.dumps(_fetch_session_detail(state, session_id, _MAX_SESSION_DETAIL_TRACES), indent=2)
+
+
@tool
def list_recent_report_runs(
state: Annotated[dict, InjectedState],
@@ -1336,42 +1503,73 @@ def add_section(
add_section.__doc__ = (add_section.__doc__ or "").replace("{max_sections}", str(MAX_REPORT_SECTIONS))
+def _validate_citation_ids(
+ state: dict, target: str, generation_id: str, trace_id: str, session_id: str
+) -> str | Citation:
+ """Return the citation to store, or an error string explaining what the agent got wrong."""
+ if target != GENERATION_TARGET and generation_id:
+ return f"Error: generation_id must be empty for {target}-target citations"
+ if target != SESSION_TARGET and session_id:
+ return f"Error: session_id must be empty for {target}-target citations"
+
+ if target == GENERATION_TARGET and not _UUID_RE.fullmatch(generation_id or ""):
+ return f"Error: generation_id {generation_id!r} is not a canonical UUID"
+
+ normalized_trace_id = _normalize_opaque_id(trace_id)
+ # Session citations point at the session; naming a trace inside it is optional extra precision.
+ if normalized_trace_id is None and target != SESSION_TARGET:
+ return "Error: trace_id is empty, too long, or contains control characters"
+ if normalized_trace_id is not None and target != GENERATION_TARGET:
+ if not _is_allowlisted(state, TRACE_ID_ALLOWLIST_KEY, normalized_trace_id):
+ return "Error: trace_id was not returned by an evaluation query for this report"
+
+ normalized_session_id = ""
+ if target == SESSION_TARGET:
+ candidate = _normalize_opaque_id(session_id)
+ if candidate is None:
+ return "Error: session_id is empty, too long, or contains control characters"
+ if not _is_allowlisted(state, SESSION_ID_ALLOWLIST_KEY, candidate):
+ return "Error: session_id was not returned by an evaluation query for this report"
+ normalized_session_id = candidate
+
+ return Citation(
+ generation_id=generation_id,
+ trace_id=normalized_trace_id or "",
+ session_id=normalized_session_id,
+ )
+
+
@tool
def add_citation(
state: Annotated[dict, InjectedState],
- generation_id: str,
- trace_id: str,
- reason: str,
+ generation_id: str = "",
+ trace_id: str = "",
+ reason: str = "",
+ session_id: str = "",
) -> str:
- """Cite a specific trace that supports a finding in the report.
+ """Cite a specific example that supports a finding in the report.
Citations are structured references that downstream consumers (signals, inbox,
coding agents) can filter on without parsing prose. Verify the target with the
- target-specific detail tool before citing it. Trace-level citations leave
- generation_id empty.
+ target-specific detail tool before citing it. Pass the ID of the unit this
+ evaluation runs on, and leave the IDs for other targets empty.
Args:
- generation_id: UUID of the $ai_generation event, or empty for a trace target.
- trace_id: Opaque ID of the cited trace.
+ generation_id: UUID of the $ai_generation event. Generation targets only.
+ trace_id: Opaque ID of the cited trace. Required for generation and trace
+ targets; optional on a session target to point at one trace inside it.
reason: Short free-form reason for the citation, e.g. "high_cost",
"refusal", "regression_at_14:00", "empty_output".
+ session_id: Opaque ID of the cited session. Session targets only.
"""
- evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))
- if evaluation_target == TRACE_TARGET and generation_id:
- return "Error: generation_id must be empty for trace-target citations"
- if evaluation_target == GENERATION_TARGET and not _UUID_RE.fullmatch(generation_id or ""):
- return f"Error: generation_id {generation_id!r} is not a canonical UUID"
- normalized_trace_id = _normalize_trace_id(trace_id)
- if normalized_trace_id is None:
- return "Error: trace_id is empty, too long, or contains control characters"
- if evaluation_target == TRACE_TARGET and not _is_returned_trace_id(state, normalized_trace_id):
- return "Error: trace_id was not returned by an evaluation query for this report"
- clean_reason = (reason or "").strip()[:200]
- state["report"].citations.append(
- Citation(generation_id=generation_id, trace_id=normalized_trace_id, reason=clean_reason)
- )
- cited_id = generation_id or normalized_trace_id
- return f"Citation {len(state['report'].citations)} added: {cited_id[:32]} ({clean_reason!r})"
+ target = resolve_evaluation_target(state.get("evaluation_target"))
+ citation = _validate_citation_ids(state, target, generation_id, trace_id, session_id)
+ if isinstance(citation, str):
+ return citation
+
+ citation.reason = (reason or "").strip()[:200]
+ state["report"].citations.append(citation)
+ return f"Citation {len(state['report'].citations)} added: {citation.cited_id()[:32]} ({citation.reason!r})"
_COMMON_OVERVIEW_TOOLS: list[BaseTool] = [
@@ -1385,19 +1583,24 @@ _COMMON_FOLLOWUP_TOOLS: list[BaseTool] = [
get_report_run,
]
-_GENERATION_DETAIL_TOOLS: list[BaseTool] = [sample_generation_details, get_generation_detail, get_generation_text_repr]
-_TRACE_DETAIL_TOOLS: list[BaseTool] = [sample_trace_details, get_trace_detail]
_OUTPUT_TOOLS: list[BaseTool] = [
set_title,
add_section,
add_citation,
]
+# Session reports keep the trace tools: a session is a bag of traces, so the way to read one is
+# to map it and then open the traces that matter.
+_DETAIL_TOOLS_BY_TARGET: dict[str, list[BaseTool]] = {
+ GENERATION_TARGET: [sample_generation_details, get_generation_detail, get_generation_text_repr],
+ TRACE_TARGET: [sample_trace_details, get_trace_detail],
+ SESSION_TARGET: [sample_session_details, get_session_detail, get_trace_detail],
+}
+
def get_eval_report_tools(evaluation_target: str, output_type: str = "boolean") -> list[BaseTool]:
"""Return the shared report tools plus only the tools relevant to this evaluation."""
- target = resolve_evaluation_target(evaluation_target)
- detail_tools = _TRACE_DETAIL_TOOLS if target == TRACE_TARGET else _GENERATION_DETAIL_TOOLS
+ detail_tools = _DETAIL_TOOLS_BY_TARGET[resolve_evaluation_target(evaluation_target)]
reasoning_tools = [] if output_type == "sentiment" else [get_top_outcome_reasons]
return [*_COMMON_OVERVIEW_TOOLS, *detail_tools, *_COMMON_FOLLOWUP_TOOLS, *reasoning_tools, *_OUTPUT_TOOLS]
diff --git a/posthog/temporal/ai_observability/eval_reports/targets.py b/posthog/temporal/ai_observability/eval_reports/targets.py
index 0e57d72867fe..4e3b6a35f4cf 100644
--- a/posthog/temporal/ai_observability/eval_reports/targets.py
+++ b/posthog/temporal/ai_observability/eval_reports/targets.py
@@ -1,18 +1,79 @@
-"""Evaluation-target helpers shared by report queries and activities."""
+"""Evaluation-target descriptors shared by report queries, tools, and prompts.
+
+One entry per target, so adding a target is adding a row here rather than another
+`if target == ...` branch in every consumer.
+"""
+
+from dataclasses import dataclass
GENERATION_TARGET = "generation"
TRACE_TARGET = "trace"
+SESSION_TARGET = "session"
+
+TRACE_ID_ALLOWLIST_KEY = "trace_id_allowlist"
+SESSION_ID_ALLOWLIST_KEY = "session_id_allowlist"
+
+
+@dataclass(frozen=True, kw_only=True)
+class EvaluationTargetDescriptor:
+ """Everything the report pipeline needs to know about one evaluation target.
+
+ `event_id_space` is the `$ai_target_type` the evaluation emitter writes. Generation
+ predates the property, so its events carry `generation_uuid` or nothing at all.
+
+ `allowlist_key` names the agent-state list of IDs this target's evaluation queries
+ returned. Detail tools refuse IDs that aren't on it, so the agent can only inspect
+ units its own report period actually surfaced.
+ """
+
+ name: str
+ unit_label: str
+ id_key: str
+ event_id_space: str | None
+ allowlist_key: str | None
+
+
+_DESCRIPTORS: dict[str, EvaluationTargetDescriptor] = {
+ GENERATION_TARGET: EvaluationTargetDescriptor(
+ name=GENERATION_TARGET,
+ unit_label="generation",
+ id_key="generation_id",
+ event_id_space=None,
+ allowlist_key=None,
+ ),
+ TRACE_TARGET: EvaluationTargetDescriptor(
+ name=TRACE_TARGET,
+ unit_label="trace",
+ id_key="trace_id",
+ event_id_space="trace_id",
+ allowlist_key=TRACE_ID_ALLOWLIST_KEY,
+ ),
+ SESSION_TARGET: EvaluationTargetDescriptor(
+ name=SESSION_TARGET,
+ unit_label="session",
+ id_key="session_id",
+ event_id_space="session_id",
+ allowlist_key=SESSION_ID_ALLOWLIST_KEY,
+ ),
+}
+
+EVALUATION_TARGETS: tuple[str, ...] = tuple(_DESCRIPTORS)
def resolve_evaluation_target(target: str | None) -> str:
normalized_target = target or GENERATION_TARGET
- if normalized_target not in (GENERATION_TARGET, TRACE_TARGET):
+ if normalized_target not in _DESCRIPTORS:
raise ValueError(f"Unsupported evaluation target: {normalized_target}")
return normalized_target
+def get_target_descriptor(target: str | None) -> EvaluationTargetDescriptor:
+ return _DESCRIPTORS[resolve_evaluation_target(target)]
+
+
def target_event_predicate(target: str | None) -> str:
"""Return a fixed SQL predicate for the evaluation event's target ID space."""
- if resolve_evaluation_target(target) == TRACE_TARGET:
- return "properties.$ai_target_type = 'trace_id'"
+ id_space = get_target_descriptor(target).event_id_space
+ if id_space is not None:
+ return f"properties.$ai_target_type = '{id_space}'"
return "(properties.$ai_target_type = 'generation_uuid' OR isNull(properties.$ai_target_type))"
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
index 786557bc9f8f..e0ff64a39be8 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
@@ -24,6 +24,7 @@ from posthog.temporal.ai_observability.eval_reports.activities import (
store_report_run_activity,
)
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import EvalReportContent, EvalReportMetrics
+from posthog.temporal.ai_observability.eval_reports.targets import target_event_predicate
from posthog.temporal.ai_observability.eval_reports.types import (
RunEvalReportAgentInput,
StoreReportRunInput,
@@ -119,6 +120,17 @@ class TestEvaluationTargetLoading(BaseTest):
self.assertEqual(target, "trace")
+ "target,expected",
+ [
+ ("session", "properties.$ai_target_type = 'session_id'"),
+ ("trace", "properties.$ai_target_type = 'trace_id'"),
+ ],
+)
+def test_target_event_predicate_per_target(target, expected):
+ assert target_event_predicate(target) == expected
+
+
@pytest.mark.parametrize(
("output_type", "evaluation_target"),
[("sentiment", "generation"), ("boolean", "trace")],
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py b/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
index fa1cd1c86176..79b973d1ae37 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
@@ -5,6 +5,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
from posthog.temporal.ai_observability.eval_reports.delivery import (
+ CitationMap,
_build_citation_map,
_format_period_for_display,
_inline_email_styles,
@@ -24,7 +25,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
)
-def _generation_citation_map(generation_id: str, trace_id: str) -> dict[str, tuple[str, str | None]]:
+def _generation_citation_map(generation_id: str, trace_id: str) -> CitationMap:
return _build_citation_map([Citation(generation_id=generation_id, trace_id=trace_id, reason="example")])
@@ -105,6 +106,15 @@ class TestLinkifyCitations(SimpleTestCase):
"/traces/trace%252Fid%2520%253F%2523",
False,
),
+ # A session citation may name a trace inside it, but the reader wants the session:
+ # that is the unit that was evaluated and what the finding is about.
+ (
+ "session",
+ Citation(session_id="session/id ?#", trace_id="trace-inside", reason="example"),
+ "session/id ?#",
+ "/sessions/session%2Fid%20%3F%23",
+ False,
+ ),
]
)
def test_links_structured_citation_for_target(
diff --git a/posthog/temporal/ai_observability/evaluation_hog.py b/posthog/temporal/ai_observability/evaluation_hog.py
index c3943979cd30..78eeb5acb5ba 100644
--- a/posthog/temporal/ai_observability/evaluation_hog.py
+++ b/posthog/temporal/ai_observability/evaluation_hog.py
@@ -167,6 +167,55 @@ def execute_hog_eval_bytecode(bytecode: list, globals_dict: dict[str, Any], allo
return result
+def finalize_hog_eval_result(result: dict[str, Any], *, allows_na: bool, unit_label: str) -> EvaluationActivityResult:
+ """Turn raw Hog bytecode output into an activity result.
+
+ Shared by the trace and session Hog activities: this is the block that decides whether a
+ failure is our bug or the customer's, and a drifted copy would mean a broken evaluation
+ silently retrying against every unit instead of disabling itself. `unit_label`
+ ("trace" / "session") reaches only the raised our-bug message, so whoever triages the page
+ can tell which target produced it.
+ """
+ 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 ({unit_label}): {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 unit). Marked terminal so the workflow disables the broken
+ # eval instead of re-running it against every matching unit (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
+
+
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.
diff --git a/posthog/temporal/ai_observability/evaluation_payload.py b/posthog/temporal/ai_observability/evaluation_payload.py
new file mode 100644
index 000000000000..fc217becc7ff
--- /dev/null
+++ b/posthog/temporal/ai_observability/evaluation_payload.py
@@ -0,0 +1,66 @@
+"""Payload-size budget shared by the trace and session evaluation fetches.
+
+The event-count caps (`MAX_TRACE_EVAL_EVENTS`, `MAX_SESSION_EVAL_EVENTS`) bound how many rows an
+evaluation pulls, which is a poor proxy for what actually costs memory: 2,500 near-limit events and
+2,500 one-line events are the same number and wildly different payloads. This module adds the
+missing dimension — bytes — measured on the preflight scan both fetches already run, before
+anything is aggregated into `groupArray`, shipped to the worker and turned into Python objects.
+
+Order matters. The row count stays the first check because it is free; the byte sum forces
+ClickHouse to decompress the payload columns, so it only runs once the count has passed. That keeps
+a runaway session id cheap to reject and reserves the expensive question for plausible units.
+
+Sits in its own module because `run_trace_evaluation` and `run_session_evaluation` must not import
+each other (see the docstring on `run_session_evaluation`).
+"""
+
+from typing import Literal
+
+from posthog.temporal.ai_observability.metrics import increment_payload_budget
+
+# Columns the evaluation fetches materialize. `properties` is included because it travels with
+# every event even though the judge transcript never renders most of it — it is real bytes in the
+# worker either way, and the Hog `evaluation_events` global exposes it directly.
+PAYLOAD_BYTES_EXPR = (
+ "sum(length(properties)"
+ " + length(ifNull(input, ''))"
+ " + length(ifNull(output, ''))"
+ " + length(ifNull(output_choices, ''))"
+ " + length(ifNull(input_state, ''))"
+ " + length(ifNull(output_state, ''))"
+ " + length(ifNull(tools, '')))"
+)
+
+# Raw payload runs larger than the transcript rendered from it: properties, states and tool
+# definitions are all bytes in the worker but mostly never reach the judge. This multiple is a
+# judgment call with headroom for that gap, anchored to a number that was already reasoned about
+# per target rather than invented alongside it. The trace side is deliberately log-only for now
+# (see `should_skip_for_payload`), which is how we find out whether this multiple is wrong before
+# it can skip anything.
+PAYLOAD_BYTES_PER_JUDGE_CHAR = 8
+
+
+def payload_budget_bytes(judge_max_chars: int) -> int:
+ """Payload ceiling for a target, derived from that target's judge transcript budget."""
+ return judge_max_chars * PAYLOAD_BYTES_PER_JUDGE_CHAR
+
+
+def should_skip_for_payload(
+ *,
+ target: Literal["trace", "session"],
+ payload_bytes: int,
+ budget_bytes: int,
+) -> bool:
+ """Record the outcome and say whether the fetch should skip.
+
+ Session enforces. Trace only records that it *would* have skipped: trace evaluations are
+ already shipped and running, so enforcing a brand-new dimension on them would start silently
+ skipping units that evaluate fine today. The metric gives us the real distribution first;
+ flipping trace to enforcing is a deliberate follow-up, not an accident of this change.
+ """
+ over_budget = payload_bytes > budget_bytes
+ if not over_budget:
+ increment_payload_budget("within_budget", target=target)
+ return False
+ increment_payload_budget("over_budget" if target == "session" else "over_budget_not_enforced", target=target)
+ return target == "session"
diff --git a/posthog/temporal/ai_observability/metrics.py b/posthog/temporal/ai_observability/metrics.py
index df42ca1f5abd..960a6c074af9 100644
--- a/posthog/temporal/ai_observability/metrics.py
+++ b/posthog/temporal/ai_observability/metrics.py
@@ -104,15 +104,28 @@ def increment_user_errors(error_type: str, *, provider: str | None = None) -> No
counter.add(1)
-def increment_settle_poll(outcome: str) -> None:
- """Track trace settle-poll activity outcomes (not_visible/not_settled/settled).
+def increment_payload_budget(outcome: str, target: str) -> None:
+ """Track payload-budget outcomes per target.
+
+ `over_budget_not_enforced` is the trace signal: it says the unit would have been skipped had
+ trace been enforcing, which is the data needed before it can be.
+ """
+ if not activity.in_activity() and not workflow.in_workflow():
+ return
+ meter = get_metric_meter({"outcome": outcome, "target": target})
+ counter = meter.create_counter("llma_eval_payload_budget", "Evaluation payload budget outcomes")
+ counter.add(1)
+
+
+def increment_settle_poll(outcome: str, target: str = "trace") -> None:
+ """Track settle-poll activity outcomes (not_visible/not_settled/settled) per target.
Safe to call outside Temporal context (no-ops), matching `increment_errors`.
"""
if not activity.in_activity() and not workflow.in_workflow():
return
- meter = get_metric_meter({"outcome": outcome})
- counter = meter.create_counter("llma_eval_settle_polls", "Trace settle poll outcomes")
+ meter = get_metric_meter({"outcome": outcome, "target": target})
+ counter = meter.create_counter("llma_eval_settle_polls", "Settle poll outcomes")
counter.add(1)
diff --git a/posthog/temporal/ai_observability/run_aggregate_evaluation.py b/posthog/temporal/ai_observability/run_aggregate_evaluation.py
index 8536181bca2f..d251aa48bf37 100644
--- a/posthog/temporal/ai_observability/run_aggregate_evaluation.py
+++ b/posthog/temporal/ai_observability/run_aggregate_evaluation.py
@@ -28,6 +28,7 @@ from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import Product, tags_context
from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.models.team import Team
from posthog.temporal.ai_observability.evaluation_errors import is_terminal_user_error_result
@@ -44,6 +45,12 @@ from posthog.temporal.ai_observability.run_evaluation import (
handle_llm_judge_activity_error,
handle_terminal_user_error_result,
)
+from posthog.temporal.ai_observability.run_session_evaluation import (
+ ExecuteSessionEvaluationInputs,
+ execute_session_hog_eval_activity,
+ execute_session_llm_judge_activity,
+ session_fetch_lookback,
+)
from posthog.temporal.ai_observability.run_trace_evaluation import (
TRACE_EVENTS_LOOKBACK,
EmitTraceEvaluationEventInputs,
@@ -56,6 +63,17 @@ from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.utils import close_db_connections
from products.ai_observability.backend.models.evaluation_configs import (
+ DEFAULT_SETTLE_STRATEGY_BY_TARGET,
+ MAX_SESSION_EVAL_EVENTS,
+ SESSION_EVAL_DEFAULT_MAX_AGE_SECONDS,
+ SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
+ SESSION_EVAL_DEFAULT_WINDOW_SECONDS,
+ SESSION_EVAL_MAX_MAX_AGE_SECONDS,
+ SESSION_EVAL_MAX_QUIET_PERIOD_SECONDS,
+ SESSION_EVAL_MAX_WINDOW_SECONDS,
+ SESSION_EVAL_MIN_MAX_AGE_SECONDS,
+ SESSION_EVAL_MIN_QUIET_PERIOD_SECONDS,
+ SESSION_EVAL_MIN_WINDOW_SECONDS,
TRACE_EVAL_DEFAULT_MAX_AGE_SECONDS,
TRACE_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
@@ -126,15 +144,103 @@ def check_trace_settled_activity(inputs: CheckTraceSettledInputs) -> str:
# Nothing visible yet (ingestion lag, replica flap, or a trace that never reached
# ClickHouse): keep polling — the max-age cap is the backstop. Settling on NULL
# would manufacture a trace_not_found verdict out of a lag spike.
- increment_settle_poll("not_visible")
+ increment_settle_poll("not_visible", target="trace")
raise ApplicationError("no trace activity visible yet", type="trace_not_settled")
if last_seen.tzinfo is None:
last_seen = last_seen.replace(tzinfo=UTC)
quiet_for = (datetime.now(UTC) - last_seen).total_seconds()
if quiet_for < inputs.quiet_period_seconds + INGESTION_LAG_MARGIN_SECONDS:
- increment_settle_poll("not_settled")
+ increment_settle_poll("not_settled", target="trace")
raise ApplicationError(f"trace active {int(quiet_for)}s ago", type="trace_not_settled")
- increment_settle_poll("settled")
+ increment_settle_poll("settled", target="trace")
+ return last_seen.isoformat()
+
+
+# Same liveness rules as the trace poll, keyed on session_id instead. `session_id` is
+# Nullable(String), so equality against a non-null constant already excludes NULL rows.
+#
+# Access path differs from the trace poll: session_id is not in the sort key, so pruning is the
+# team_id prefix plus the idx_session_id bloom filter (0.01 false-positive rate). The partition key
+# is toYYYYMM(drop_date), which derives from timestamp plus a per-row retention_days, so no
+# timestamp predicate prunes partitions — the _timestamp bound only filters within selected
+# granules. count() rides the same scan, which is what makes the runaway-session guard free.
+_SESSION_SETTLE_POLL_SQL = """
+SELECT maxOrNull(_timestamp) AS last_seen, count() AS event_count
+FROM posthog.ai_events AS ai_events
+WHERE event IN {liveness_events}
+ AND session_id = {session_id}
+ AND _timestamp >= {date_from}
+"""
+
+
+# Whether a session is small enough to evaluate is decided by one number in one place: the fetch
+# preflight's `MAX_SESSION_EVAL_EVENTS`, which counts exactly the rows the fetch reads, over the
+# same window and clock. This is not that number. It is a circuit breaker whose only job is to stop
+# a runaway session id (a constant "0", an id shared across every conversation) from holding a
+# workflow open for its entire max_age. It counts liveness events over the settle window, so it
+# undercounts a long session by construction — fine for a circuit breaker, and exactly why it must
+# sit far above the evaluation cap rather than pretending to be it.
+SESSION_RUNAWAY_CIRCUIT_BREAKER_EVENTS = 10 * MAX_SESSION_EVAL_EVENTS
+
+
+@dataclass
+class CheckSessionSettledInputs:
+ team_id: int
+ session_id: str
+ quiet_period_seconds: int
+ lookback_seconds: int
+ runaway_events: int = SESSION_RUNAWAY_CIRCUIT_BREAKER_EVENTS
+
+ @property
+ def properties_to_log(self) -> dict[str, Any]:
+ return {"team_id": self.team_id, "session_id": self.session_id}
+
+
+@close_db_connections
+def check_session_settled_activity(inputs: CheckSessionSettledInputs) -> str:
+ """One settle probe for a session. Raises the retryable `session_not_settled` error until the
+ session has had no structural activity for quiet_period + margin; the activity's retry
+ schedule is the poll loop, so this function never sleeps."""
+ team = Team.objects.get(id=inputs.team_id)
+ # Tagged like every other AI-observability query so it routes to the LLM_ANALYTICS ClickHouse
+ # user and takes its concurrency slot; untagged, a settling session's polls compete with
+ # interactive traffic on the default user.
+ with tags_context(product=Product.LLM_ANALYTICS):
+ result = query_ai_events(
+ query=parse_select(_SESSION_SETTLE_POLL_SQL),
+ placeholders={
+ "liveness_events": ast.Constant(value=list(_LIVENESS_EVENTS)),
+ "session_id": ast.Constant(value=inputs.session_id),
+ "date_from": ast.Constant(value=datetime.now(UTC) - timedelta(seconds=inputs.lookback_seconds)),
+ },
+ team=team,
+ query_type="SessionSettlePoll",
+ fall_back_to_events=False,
+ workload=Workload.OFFLINE,
+ )
+ row = result.results[0] if result.results else (None, 0)
+ last_seen, event_count = row[0], int(row[1] or 0)
+ if event_count > inputs.runaway_events:
+ # Stop waiting immediately rather than sitting out max_age. The fetch still decides the
+ # actual outcome and reports the real reason; this only bounds how long we wait for it.
+ increment_settle_poll("runaway", target="session")
+ raise ApplicationError(
+ f"session has {event_count} events in the settle window, over the "
+ f"{inputs.runaway_events} runaway threshold",
+ type="session_runaway",
+ non_retryable=True,
+ )
+ if last_seen is None:
+ increment_settle_poll("not_visible", target="session")
+ raise ApplicationError("no session activity visible yet", type="session_not_settled")
+ if last_seen.tzinfo is None:
+ last_seen = last_seen.replace(tzinfo=UTC)
+ quiet_for = (datetime.now(UTC) - last_seen).total_seconds()
+ if quiet_for < inputs.quiet_period_seconds + INGESTION_LAG_MARGIN_SECONDS:
+ increment_settle_poll("not_settled", target="session")
+ raise ApplicationError(f"session active {int(quiet_for)}s ago", type="session_not_settled")
+ increment_settle_poll("settled", target="session")
return last_seen.isoformat()
@@ -144,34 +250,70 @@ def _clamp(value: Any, floor: int, ceiling: int, default: int) -> int:
return int(min(max(value, floor), ceiling))
-def resolve_settle_plan(settle: dict[str, Any] | None) -> tuple[str, int, int]:
+# (floor, ceiling, default) per field, per target. The workflow re-clamps what the serializer
+# already validated, so a payload written before a bound moved can never wedge the settle phase.
+_SETTLE_BOUNDS: dict[str, dict[str, tuple[int, int, int]]] = {
+ "trace": {
+ "window": (TRACE_EVAL_MIN_WINDOW_SECONDS, TRACE_EVAL_MAX_WINDOW_SECONDS, TRACE_EVAL_DEFAULT_WINDOW_SECONDS),
+ "quiet": (
+ TRACE_EVAL_MIN_QUIET_PERIOD_SECONDS,
+ TRACE_EVAL_MAX_QUIET_PERIOD_SECONDS,
+ TRACE_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
+ ),
+ "max_age": (TRACE_EVAL_MIN_MAX_AGE_SECONDS, TRACE_EVAL_MAX_MAX_AGE_SECONDS, TRACE_EVAL_DEFAULT_MAX_AGE_SECONDS),
+ },
+ "session": {
+ "window": (
+ SESSION_EVAL_MIN_WINDOW_SECONDS,
+ SESSION_EVAL_MAX_WINDOW_SECONDS,
+ SESSION_EVAL_DEFAULT_WINDOW_SECONDS,
+ ),
+ "quiet": (
+ SESSION_EVAL_MIN_QUIET_PERIOD_SECONDS,
+ SESSION_EVAL_MAX_QUIET_PERIOD_SECONDS,
+ SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
+ ),
+ "max_age": (
+ SESSION_EVAL_MIN_MAX_AGE_SECONDS,
+ SESSION_EVAL_MAX_MAX_AGE_SECONDS,
+ SESSION_EVAL_DEFAULT_MAX_AGE_SECONDS,
+ ),
+ },
+}
+
+
+# Ceiling on poll activities per settling run. Sessions accept quiet=10s alongside max_age=7d, and
+# a cadence derived from the quiet period alone would schedule ~60k ClickHouse aggregates for one
+# (evaluation, session). Large enough that no in-bounds trace config is affected, so in-flight trace
+# runs replay with an unchanged retry policy.
+MAX_SETTLE_POLLS_PER_RUN = 1000
+
+
+def resolve_poll_interval(primary_seconds: int, poll_budget_seconds: int) -> int:
+ """Seconds between settle probes: a quarter of the quiet period, floored so a long max-age
+ budget can't turn a short quiet period into tens of thousands of polls.
+
+ The budget floor rounds up, so the ceiling holds exactly rather than off by one.
+ """
+ budget_floor = -(-poll_budget_seconds // MAX_SETTLE_POLLS_PER_RUN)
+ return max(primary_seconds // 4, budget_floor, 10)
+
+
+def resolve_settle_plan(settle: dict[str, Any] | None, target: str = "trace") -> tuple[str, int, int]:
"""Resolve the settle config into (strategy, primary_seconds, max_age_seconds).
Deterministic and exception-free on purpose: the serializer already validated the stored
config, so anything malformed here is a payload bug — falling back to defaults keeps a bad
payload from wedging the workflow. max_age is coerced to cover at least one quiet period.
"""
+ bounds = _SETTLE_BOUNDS.get(target, _SETTLE_BOUNDS["trace"])
config = settle or {}
- if config.get("strategy") == "inactivity":
- quiet = _clamp(
- config.get("quiet_period_seconds"),
- TRACE_EVAL_MIN_QUIET_PERIOD_SECONDS,
- TRACE_EVAL_MAX_QUIET_PERIOD_SECONDS,
- TRACE_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
- )
- max_age = _clamp(
- config.get("max_age_seconds"),
- TRACE_EVAL_MIN_MAX_AGE_SECONDS,
- TRACE_EVAL_MAX_MAX_AGE_SECONDS,
- TRACE_EVAL_DEFAULT_MAX_AGE_SECONDS,
- )
+ strategy = config.get("strategy") or DEFAULT_SETTLE_STRATEGY_BY_TARGET.get(target, "fixed_window")
+ if strategy == "inactivity":
+ quiet = _clamp(config.get("quiet_period_seconds"), *bounds["quiet"])
+ max_age = _clamp(config.get("max_age_seconds"), *bounds["max_age"])
return ("inactivity", quiet, max(max_age, quiet))
- window = _clamp(
- config.get("window_seconds"),
- TRACE_EVAL_MIN_WINDOW_SECONDS,
- TRACE_EVAL_MAX_WINDOW_SECONDS,
- TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
- )
+ window = _clamp(config.get("window_seconds"), *bounds["window"])
return ("fixed_window", window, window)
@@ -182,6 +324,8 @@ class RunAggregateEvaluationInputs:
trace_id: str
distinct_id: str
session_id: str | None = None
+ ai_session_id: str | None = None
+ target: str = "trace"
settle: dict[str, Any] | None = None
@property
@@ -191,6 +335,7 @@ class RunAggregateEvaluationInputs:
"evaluation_id": self.evaluation_id,
"team_id": self.team_id,
"trace_id": self.trace_id,
+ "target": self.target,
}
@@ -202,13 +347,24 @@ def _is_schedule_to_close_timeout(error: temporalio.exceptions.ActivityError) ->
)
+# Both poll activities signal "keep waiting" with their own error type. This must stay a set
+# rather than become a rename: `trace_not_settled` is recorded in the history of every in-flight
+# trace run, and replay has to keep matching it.
+_NOT_SETTLED_ERROR_TYPES = frozenset({"trace_not_settled", "session_not_settled"})
+
+
def _is_still_not_settled(error: temporalio.exceptions.ActivityError) -> bool:
# Temporal delivers the last attempt's own failure once retries run out of
# schedule-to-close budget rather than synthesizing a timeout — the first probe
- # fires immediately, so there's always a prior `trace_not_settled` failure to
- # report by the time the budget is exhausted.
+ # fires immediately, so there's always a prior not-settled failure to report by
+ # the time the budget is exhausted.
+ cause = error.cause
+ return isinstance(cause, ApplicationError) and cause.type in _NOT_SETTLED_ERROR_TYPES
+
+
+def _is_session_runaway(error: temporalio.exceptions.ActivityError) -> bool:
cause = error.cause
- return isinstance(cause, ApplicationError) and cause.type == "trace_not_settled"
+ return isinstance(cause, ApplicationError) and cause.type == "session_runaway"
@temporalio.workflow.defn(name="run-aggregate-evaluation")
@@ -221,7 +377,17 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):
async def run(self, inputs: RunAggregateEvaluationInputs) -> WorkflowResult:
window_start = temporalio.workflow.now()
- strategy, primary_seconds, max_age_seconds = resolve_settle_plan(inputs.settle)
+ # Fail loudly rather than falling through to the trace path, which would grade `trace_id`
+ # and emit a trace-shaped verdict under a session evaluation's name. Unreachable from the
+ # scheduler, which drops these as `no_ai_session_id`; this is the backstop for a malformed
+ # payload or a manual start. Emits no command, so trace histories replay unchanged.
+ if inputs.target == "session" and inputs.ai_session_id is None:
+ raise ApplicationError(
+ "A session-target evaluation needs an $ai_session_id", type="missing_ai_session_id", non_retryable=True
+ )
+
+ strategy, primary_seconds, max_age_seconds = resolve_settle_plan(inputs.settle, inputs.target)
+ is_session = inputs.target == "session" and inputs.ai_session_id is not None
if strategy == "inactivity":
# Sleep past the lag margin too: a probe at exactly quiet_period can never pass
# the `quiet_period + margin` settled bar, so it would burn a poll for nothing.
@@ -229,34 +395,52 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):
await asyncio.sleep(initial_sleep_seconds)
poll_budget_seconds = max_age_seconds - initial_sleep_seconds
if poll_budget_seconds > 0:
- poll_interval = max(primary_seconds // 4, 10)
+ poll_interval = resolve_poll_interval(primary_seconds, poll_budget_seconds)
+ retry_policy = RetryPolicy(
+ initial_interval=timedelta(seconds=poll_interval),
+ backoff_coefficient=1.0,
+ maximum_attempts=0,
+ )
try:
- await temporalio.workflow.execute_activity(
- check_trace_settled_activity,
- CheckTraceSettledInputs(
- team_id=inputs.team_id,
- trace_id=inputs.trace_id,
- quiet_period_seconds=primary_seconds,
- ),
- start_to_close_timeout=timedelta(seconds=30),
- schedule_to_close_timeout=timedelta(seconds=poll_budget_seconds),
- retry_policy=RetryPolicy(
- initial_interval=timedelta(seconds=poll_interval),
- backoff_coefficient=1.0,
- maximum_attempts=0,
- ),
- )
+ if is_session and inputs.ai_session_id is not None:
+ await temporalio.workflow.execute_activity(
+ check_session_settled_activity,
+ CheckSessionSettledInputs(
+ team_id=inputs.team_id,
+ session_id=inputs.ai_session_id,
+ quiet_period_seconds=primary_seconds,
+ lookback_seconds=int(session_fetch_lookback(max_age_seconds).total_seconds()),
+ ),
+ start_to_close_timeout=timedelta(seconds=30),
+ schedule_to_close_timeout=timedelta(seconds=poll_budget_seconds),
+ retry_policy=retry_policy,
+ )
+ else:
+ await temporalio.workflow.execute_activity(
+ check_trace_settled_activity,
+ CheckTraceSettledInputs(
+ team_id=inputs.team_id,
+ trace_id=inputs.trace_id,
+ quiet_period_seconds=primary_seconds,
+ ),
+ start_to_close_timeout=timedelta(seconds=30),
+ schedule_to_close_timeout=timedelta(seconds=poll_budget_seconds),
+ retry_policy=retry_policy,
+ )
except temporalio.exceptions.ActivityError as e:
- # A schedule-to-close or still-not-settled timeout means the trace never settled
- # within max_age — anything else is a real failure and should propagate.
- if not (_is_schedule_to_close_timeout(e) or _is_still_not_settled(e)):
+ if _is_session_runaway(e):
+ # Stop waiting; the fetch's own preflight decides the outcome and reports
+ # the real reason, so no skip result has to be synthesized here.
+ pass
+ elif _is_schedule_to_close_timeout(e) or _is_still_not_settled(e):
+ # Temporal stops polling once the next retry would overrun schedule-to-close, so it
+ # can give up as much as one poll_interval before max_age. Wait out the remainder so
+ # we always honor the full max-age window before grading a still-active unit.
+ remaining = max_age_seconds - (temporalio.workflow.now() - window_start).total_seconds()
+ if remaining > 0:
+ await asyncio.sleep(remaining)
+ else:
raise
- # Temporal stops polling once the next retry would overrun schedule-to-close, so it
- # can give up as much as one poll_interval before max_age. Wait out the remainder so
- # we always honor the full max-age window before grading a still-active trace.
- remaining = max_age_seconds - (temporalio.workflow.now() - window_start).total_seconds()
- if remaining > 0:
- await asyncio.sleep(remaining)
elif primary_seconds:
await asyncio.sleep(primary_seconds)
@@ -282,36 +466,65 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):
}
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),
+ if is_session and inputs.ai_session_id is not None:
+ session_inputs = ExecuteSessionEvaluationInputs(
+ evaluation=evaluation,
+ team_id=inputs.team_id,
+ session_id=inputs.ai_session_id,
+ window_start=window_start.isoformat(),
)
+ if evaluation_type == "hog":
+ result = await temporalio.workflow.execute_activity(
+ execute_session_hog_eval_activity,
+ session_inputs,
+ # Longer than the trace equivalent: the fetch spans every trace of the session.
+ schedule_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ else:
+ try:
+ result = await temporalio.workflow.execute_activity(
+ execute_session_llm_judge_activity,
+ session_inputs,
+ schedule_to_close_timeout=timedelta(minutes=15),
+ 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
else:
- try:
+ 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_llm_judge_activity,
+ execute_trace_hog_eval_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,
+ schedule_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=2),
)
- 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
+ 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
if is_terminal_user_error_result(result):
return await handle_terminal_user_error_result(
@@ -331,6 +544,8 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):
session_id=inputs.session_id,
result=result,
start_time=eval_start,
+ target=inputs.target,
+ ai_session_id=inputs.ai_session_id,
),
schedule_to_close_timeout=timedelta(seconds=30),
retry_policy=RetryPolicy(maximum_attempts=3),
diff --git a/posthog/temporal/ai_observability/run_session_evaluation.py b/posthog/temporal/ai_observability/run_session_evaluation.py
new file mode 100644
index 000000000000..734faa8e6ae4
--- /dev/null
+++ b/posthog/temporal/ai_observability/run_session_evaluation.py
@@ -0,0 +1,631 @@
+"""Session-level evaluation: fetch, payload caps, Hog globals and judge transcript.
+
+Sits beside `run_trace_evaluation` rather than inside it because the shared emit activity lives
+there, and this module already imports a constant from it; if `run_trace_evaluation` ever imported
+something back from here, the two would cycle. The settle phase and the emit activity are shared;
+only the fetch-and-evaluate half is session-specific.
+"""
+
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import temporalio
+import posthoganalytics
+from temporalio.exceptions import ApplicationError
+
+from posthog.schema import DateRange, LLMTrace, SessionQuery
+
+from posthog.hogql import ast
+from posthog.hogql.constants import MAX_SELECT_TRACES_LIMIT_EXPORT
+from posthog.hogql.parser import parse_select
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import Product, tags_context
+from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
+from posthog.hogql_queries.ai.session_query_runner import SessionQueryRunner
+from posthog.models.team import Team
+from posthog.sync import database_sync_to_async
+from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io
+from posthog.temporal.ai_observability.evaluation_hog import (
+ build_hog_event_global,
+ execute_hog_eval_bytecode,
+ finalize_hog_eval_result,
+ hog_bytecode_references_global,
+)
+from posthog.temporal.ai_observability.evaluation_llm_judge import call_llm_judge, get_output_type_config
+from posthog.temporal.ai_observability.evaluation_payload import (
+ PAYLOAD_BYTES_EXPR,
+ payload_budget_bytes,
+ should_skip_for_payload,
+)
+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
+from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
+from posthog.temporal.ai_observability.run_trace_evaluation import TRACE_EVENTS_LOOKBACK
+from posthog.temporal.common.utils import close_db_connections
+
+from products.ai_observability.backend.models.evaluation_configs import (
+ EVALUATION_TEST_LOOKBACK_DAYS,
+ MAX_SESSION_EVAL_EVENTS,
+)
+from products.ai_observability.backend.text_repr.formatters import (
+ FormatterOptions,
+ format_trace_text_repr,
+ llm_trace_to_formatter_format,
+)
+
+# Sessions run ~3.5x a trace at p90 (222 events against a trace's typical handful) and the shared
+# formatter uniformly samples lines rather than truncating, so the trace's 150k budget would hand
+# the judge a shredded transcript. 500k chars is ~2.2k chars per event at p90.
+JUDGE_SESSION_MAX_CHARS = 500_000
+
+# Floor so a session with many traces still renders each one readably instead of one line each.
+_MIN_TRACE_CHARS_IN_SESSION = 2_000
+
+_SESSION_SKIP_REASONING = {
+ "session_not_found": "No session events were found within the evaluation window; evaluation skipped.",
+ "session_has_no_traces": (
+ "This session's events have no trace id, so there was nothing to evaluate. Set $ai_trace_id "
+ "on the events you want graded."
+ ),
+ # Two reasons, not one: the remedies differ. Too many events is almost always a shared session
+ # id; too much payload is a normal-length session carrying very large inputs or outputs.
+ "session_too_large": (
+ f"This session holds more than {MAX_SESSION_EVAL_EVENTS} events, which is more than one evaluation can "
+ "read. This usually means one session id is shared across several conversations, so give each "
+ "conversation its own $ai_session_id."
+ ),
+ "session_payload_too_large": (
+ "This session's events carry more data than one evaluation can hold, so it was not graded. Trim the "
+ "largest inputs and outputs, or evaluate each trace instead."
+ ),
+ "session_truncated": (
+ f"This session has more than {MAX_SELECT_TRACES_LIMIT_EXPORT} traces, which is more than one evaluation "
+ "can read, so it was not graded."
+ ),
+ "session_too_long_to_judge": (
+ "This session's transcript is too long to grade in one piece. A Hog evaluation has no transcript limit, "
+ "or you can evaluate each trace instead."
+ ),
+}
+
+# Mirrors `ai_events.retention_days`, whose DEFAULT 30 nothing currently overrides — the column
+# exists for per-row retention that no ingestion path writes yet. Keep them in step: if retention
+# ever becomes longer than this, the fetch would stop at 30 days and grade a session on its tail
+# with no way to notice, because events past their drop_date are deleted and leave nothing to
+# count. That case is undetectable from here by construction, which is why the constant matters.
+AI_EVENTS_RETENTION_DAYS = 30
+
+# Must select exactly the rows `SessionQueryRunner` will read, or the cap it gates bounds nothing.
+# Two ways the fetch is wider than a naive `session_id = X` count, both deliberate over there:
+# it reads six event types (annotations included, unlike the settle poll, where they correctly
+# don't count as liveness), and it resolves traces first, then reads every event of those traces
+# — `session_id` is per-event and nullable, so a producer that tags only the trace root would
+# otherwise preflight at 1 and fetch the whole trace. minOrNull(timestamp) rides the same scan,
+# and over this row set it means the session's real start rather than its first tagged event.
+_SESSION_EVENT_COUNT_SQL = """
+SELECT count() AS event_count, minOrNull(timestamp) AS first_seen
+FROM posthog.ai_events AS ai_events
+WHERE event IN ('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')
+ AND isNotNull(trace_id)
+ AND trace_id != ''
+ AND trace_id IN (
+ SELECT trace_id
+ FROM posthog.ai_events AS ai_events
+ WHERE session_id = {session_id}
+ AND isNotNull(trace_id)
+ AND trace_id != ''
+ AND timestamp >= {date_from}
+ AND timestamp <= {date_to}
+ )
+ AND timestamp >= {date_from}
+ AND timestamp <= {date_to}
+"""
+
+
+# Deliberately a second query rather than another aggregate on the count's scan: summing lengths
+# forces ClickHouse to decompress the payload columns, and a runaway session id should be rejected
+# by the count without ever paying for that. Only sessions that already look plausible get here.
+_SESSION_PAYLOAD_BYTES_SQL = f"""
+SELECT {PAYLOAD_BYTES_EXPR} AS payload_bytes
+FROM posthog.ai_events AS ai_events
+WHERE event IN ('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')
+ AND isNotNull(trace_id)
+ AND trace_id != ''
+ AND trace_id IN (
+ SELECT trace_id
+ FROM posthog.ai_events AS ai_events
+ WHERE session_id = {{session_id}}
+ AND isNotNull(trace_id)
+ AND trace_id != ''
+ AND timestamp >= {{date_from}}
+ AND timestamp <= {{date_to}}
+ )
+ AND timestamp >= {{date_from}}
+ AND timestamp <= {{date_to}}
+"""
+
+
+def _sum_session_payload_bytes(team: Team, session_id: str, date_from: datetime, date_to: datetime) -> int:
+ with tags_context(product=Product.LLM_ANALYTICS):
+ result = query_ai_events(
+ query=parse_select(_SESSION_PAYLOAD_BYTES_SQL),
+ placeholders={
+ "session_id": ast.Constant(value=session_id),
+ "date_from": ast.Constant(value=date_from),
+ "date_to": ast.Constant(value=date_to),
+ },
+ team=team,
+ query_type="SessionEvaluationPayloadBytes",
+ fall_back_to_events=False,
+ workload=Workload.OFFLINE,
+ )
+ if not result.results:
+ return 0
+ return int(result.results[0][0] or 0)
+
+
+def session_fetch_lookback(max_age_seconds: int) -> timedelta:
+ """How far back the settle poll's liveness/runaway-count check searches for recent activity.
+
+ Not used for the fetch's own `date_from`: `max_age_seconds` is a forward budget (how long the
+ workflow waits after the first matching generation), which says nothing about how long the
+ session was already running, so `fetch_session_for_evaluation` derives its window from the
+ session's actual first event instead. This lookback only needs to cover the settle window
+ itself, which is what `check_session_settled_activity` uses it for.
+ """
+ return max(TRACE_EVENTS_LOOKBACK, timedelta(seconds=max_age_seconds))
+
+
+@dataclass
+class SessionFetchOutcome:
+ traces: list[LLMTrace] | None
+ skip_reason: str | None
+ event_count: int
+
+
+@dataclass
+class _SessionEventCount:
+ event_count: int
+ first_seen: datetime | None
+
+
+def _count_session_events(team: Team, session_id: str, date_from: datetime, date_to: datetime) -> _SessionEventCount:
+ """Cheap preflight so a runaway session id is skipped before pulling its payload, and the
+ source of the session's real start time (see `fetch_session_for_evaluation`).
+
+ `fall_back_to_events=False` and an ungrouped aggregate on purpose: the aggregate always
+ returns exactly one row, so query_ai_events's empty-result probe never fires and a session
+ that aged out of ai_events can never silently degrade to a stripped events scan.
+ """
+ with tags_context(product=Product.LLM_ANALYTICS):
+ result = query_ai_events(
+ query=parse_select(_SESSION_EVENT_COUNT_SQL),
+ placeholders={
+ "session_id": ast.Constant(value=session_id),
+ "date_from": ast.Constant(value=date_from),
+ "date_to": ast.Constant(value=date_to),
+ },
+ team=team,
+ query_type="SessionEvaluationEventCount",
+ fall_back_to_events=False,
+ workload=Workload.OFFLINE,
+ )
+ if not result.results:
+ return _SessionEventCount(event_count=0, first_seen=None)
+ event_count, first_seen = result.results[0]
+ return _SessionEventCount(event_count=int(event_count), first_seen=first_seen)
+
+
+def fetch_session_for_evaluation(team_id: int, session_id: str, window_start: datetime) -> SessionFetchOutcome:
+ """Fetch every trace of a session for an online evaluation, bounded by retention.
+
+ Deliberately not bounded by `max_age_seconds`: that's a forward budget (how long the workflow
+ waits after the first matching generation), which says nothing about how long the session had
+ already been running when that generation arrived. So the initial preflight searches back to
+ the full retention window instead of guessing a lookback from `max_age_seconds`, reads the
+ session's real start time off the same scan (`minOrNull(timestamp)`, free per the comment on
+ `_SESSION_EVENT_COUNT_SQL`), and narrows `date_from` to that start for the actual fetch.
+ Retention is the floor: a session that began before it can't be fetched whole no matter what
+ window is chosen.
+ """
+ team = Team.objects.get(id=team_id)
+ retention_floor = window_start - timedelta(days=AI_EVENTS_RETENTION_DAYS)
+ date_to = datetime.now(UTC)
+
+ preflight = _count_session_events(team, session_id, retention_floor, date_to)
+ if preflight.event_count == 0:
+ return SessionFetchOutcome(traces=None, skip_reason="session_not_found", event_count=0)
+ if preflight.event_count > MAX_SESSION_EVAL_EVENTS:
+ return SessionFetchOutcome(traces=None, skip_reason="session_too_large", event_count=preflight.event_count)
+
+ # Only now that the row count looks plausible is it worth reading the payload columns to size it.
+ payload_bytes = _sum_session_payload_bytes(team, session_id, retention_floor, date_to)
+ if should_skip_for_payload(
+ target="session",
+ payload_bytes=payload_bytes,
+ budget_bytes=payload_budget_bytes(JUDGE_SESSION_MAX_CHARS),
+ ):
+ return SessionFetchOutcome(
+ traces=None, skip_reason="session_payload_too_large", event_count=preflight.event_count
+ )
+
+ event_count = preflight.event_count
+ date_from = preflight.first_seen or retention_floor
+ if date_from.tzinfo is None:
+ date_from = date_from.replace(tzinfo=UTC)
+ date_from = max(date_from, retention_floor)
+
+ runner = SessionQueryRunner(
+ team=team,
+ query=SessionQuery(
+ sessionId=session_id,
+ dateRange=DateRange(date_from=date_from.isoformat(), date_to=date_to.isoformat()),
+ # SessionQueryRunner defaults to DEFAULT_RETURNED_ROWS (100) under LimitContext.QUERY,
+ # which would silently drop the tail of any session past 100 traces. Ask for the same
+ # ceiling MAX_SESSION_EVAL_EVENTS already implies is plausible for a real session.
+ limit=MAX_SELECT_TRACES_LIMIT_EXPORT,
+ ),
+ for_evaluation=True,
+ )
+ response = runner.calculate()
+ if not response.results:
+ # The preflight counted rows, so events exist — the runner requires a non-empty trace id and
+ # found none. Saying "no session events were found" here would send the user looking in the
+ # wrong place.
+ return SessionFetchOutcome(traces=None, skip_reason="session_has_no_traces", event_count=event_count)
+ if response.hasMore:
+ # A session graded on part of itself must not look like a session graded whole, so skip
+ # rather than hand the judge a transcript silently missing its tail (or, combined with
+ # the runner's newest-first ordering, its opening).
+ return SessionFetchOutcome(traces=None, skip_reason="session_truncated", event_count=event_count)
+
+ traces = sorted(response.results, key=lambda trace: trace.createdAt)
+ return SessionFetchOutcome(traces=traces, skip_reason=None, event_count=event_count)
+
+
+def build_session_hog_globals(
+ traces: list[LLMTrace], session_id: str, *, bytecode: list[Any] | None = None
+) -> dict[str, Any]:
+ """Build Hog globals for a session-level eval.
+
+ Only the target-independent globals (`target`, `evaluation_events`) are built. The
+ trace-only `events` / `trace` globals exist for Hog source saved before those two landed,
+ and no such source can exist for a session target.
+ """
+ globals_dict: dict[str, Any] = {}
+ if bytecode is None or hog_bytecode_references_global(bytecode, "target"):
+ globals_dict["target"] = {
+ "type": "session",
+ "id": session_id,
+ # Summed per-trace, so this stays "time spent doing AI work", the same thing it means
+ # on the generation and trace targets. Session wall-clock is a different number and is
+ # derivable from evaluation_events timestamps.
+ "total_cost_usd": sum(trace.totalCost or 0 for trace in traces),
+ "total_latency_seconds": sum(trace.totalLatency or 0 for trace in traces),
+ }
+ if bytecode is None or hog_bytecode_references_global(bytecode, "evaluation_events"):
+ globals_dict["evaluation_events"] = [
+ build_hog_event_global(
+ event.event,
+ event.properties,
+ event_uuid=event.id,
+ timestamp=event.createdAt,
+ )
+ for trace in traces
+ for event in (trace.events or [])
+ ]
+ return globals_dict
+
+
+def build_session_system_prompt(prompt: str, allows_na: bool) -> str:
+ """Session-level variant of `build_trace_system_prompt` — frames the unit under evaluation as
+ a multi-trace conversation rather than one execution."""
+ config = get_output_type_config(allows_na)
+ return f"""You are an evaluator. Evaluate the following AI session — every trace in one \
+user's conversation, in order — according to this criteria:
+
+{prompt}
+
+{config.instructions}"""
+
+
+def format_session_for_judge(traces: list[LLMTrace]) -> str | None:
+ """Render a session as the canonical text representation, one section per trace.
+
+ The char budget is split evenly across traces so one long trace can't crowd the others out,
+ which matters for "did the user accomplish their goal" — the answer often lives in the
+ opening and closing turns, not the biggest one.
+
+ Returns `None` only when the *rendered* transcript overshoots the budget, meaning a final slice
+ would silently drop trailing traces. The caller must treat that as a `session_too_long_to_judge`
+ skip rather than judge a transcript that's missing its close.
+
+ Deliberately measured after rendering rather than from `per_trace_budget * len(traces)`: the
+ per-trace budget is a ceiling, not a prediction, and real traces render well under it. Deciding
+ on the product turned this into a hard cliff at 251 traces regardless of how little those traces
+ actually contained.
+ """
+ if not traces:
+ return ""
+ per_trace_budget = max(JUDGE_SESSION_MAX_CHARS // len(traces), _MIN_TRACE_CHARS_IN_SESSION)
+ options: FormatterOptions = {
+ "include_markers": False,
+ "collapsed": False,
+ "truncated": True,
+ "include_line_numbers": True,
+ "max_length": per_trace_budget,
+ }
+ sections: list[str] = []
+ for index, trace in enumerate(traces, start=1):
+ trace_dict, hierarchy = llm_trace_to_formatter_format(trace)
+ text, _ = format_trace_text_repr(trace_dict, hierarchy, options)
+ sections.append(f"=== Trace {index} of {len(traces)} (id: {trace.id}) ===\n{text}")
+ rendered = "\n\n".join(sections)
+ if len(rendered) > JUDGE_SESSION_MAX_CHARS:
+ return None
+ return rendered
+
+
+def build_session_skip_result(allows_na: bool, skip_reason: str) -> EvaluationActivityResult:
+ """Session mirror of `_build_trace_skip_result` — 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": _SESSION_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
+
+
+@dataclass
+class ExecuteSessionEvaluationInputs:
+ evaluation: dict[str, Any]
+ team_id: int
+ session_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"),
+ "session_id": self.session_id,
+ }
+
+
+@close_db_connections
+def execute_session_llm_judge_activity(inputs: ExecuteSessionEvaluationInputs) -> EvaluationActivityResult:
+ """Fetch the whole session and run the LLM judge over its transcript.
+
+ Fetch and judge happen in one activity on purpose: returning the session through the
+ workflow would hit Temporal's ~2 MiB payload limit.
+ """
+ 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_session_for_evaluation(
+ inputs.team_id,
+ inputs.session_id,
+ datetime.fromisoformat(inputs.window_start),
+ )
+ if outcome.skip_reason or outcome.traces is None:
+ return build_session_skip_result(allows_na, outcome.skip_reason or "session_not_found")
+
+ transcript = format_session_for_judge(outcome.traces)
+ if transcript is None:
+ return build_session_skip_result(allows_na, "session_too_long_to_judge")
+
+ return call_llm_judge(
+ evaluation=evaluation,
+ system_prompt=build_session_system_prompt(prompt, allows_na),
+ user_prompt=transcript,
+ allows_na=allows_na,
+ )
+
+
+async def execute_session_hog_eval_activity(inputs: ExecuteSessionEvaluationInputs) -> EvaluationActivityResult:
+ """Fetch the whole session and run Hog bytecode against session-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_session_for_evaluation(
+ inputs.team_id,
+ inputs.session_id,
+ datetime.fromisoformat(inputs.window_start),
+ )
+ if outcome.skip_reason or outcome.traces is None:
+ return None, outcome.skip_reason or "session_not_found"
+ globals_dict = build_session_hog_globals(outcome.traces, inputs.session_id, bytecode=bytecode)
+ 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_session_skip_result(allows_na, skip_reason or "session_not_found")
+
+ return finalize_hog_eval_result(result, allows_na=allows_na, unit_label="session")
+
+
+@dataclass
+class SessionHogTestResult:
+ """One session's outcome from `run_hog_eval_over_recent_sessions`, shaped for the editor test
+ endpoint rather than for online emission."""
+
+ session_id: str
+ verdict: bool | None
+ reasoning: str
+ error: str | None
+ input_preview: str
+ output_preview: str
+
+
+# Sessions whose structural activity has been quiet for the configured period, restricted to those
+# with a generation matching the evaluation's conditions. At a long quiet period the sample is
+# legitimately empty, and the caller says so rather than widening the window and previewing sessions
+# the evaluation has not reached yet.
+#
+# Quiet is judged on `timestamp` here, not the `_timestamp` arrival clock the online settle poll
+# uses. Not a preference: any query that can return zero rows is also compiled against the shared
+# events table — as a fallback, or as the retention probe that classifies a miss — and `_timestamp`
+# does not exist there, so a `_timestamp` predicate makes the empty sample a hard error rather than
+# an empty list. The settle poll escapes this only because its ungrouped aggregate always returns a
+# row. The cost is that a client clock running fast can make a session look quiet a little early in
+# the preview; the online settle is unaffected and still judges on arrival.
+_SESSION_TEST_SAMPLE_SQL = """
+SELECT session_id, min(timestamp) AS trigger_timestamp, max(timestamp) AS last_seen
+FROM posthog.ai_events AS ai_events
+WHERE event IN ('$ai_generation', '$ai_span', '$ai_embedding', '$ai_trace')
+ AND isNotNull(session_id)
+ AND session_id != ''
+ AND timestamp >= {date_from}
+ AND timestamp <= {date_to}
+ AND session_id IN (
+ SELECT session_id
+ FROM posthog.ai_events AS ai_events
+ WHERE event = '$ai_generation'
+ AND isNotNull(session_id)
+ AND session_id != ''
+ AND timestamp >= {date_from}
+ AND timestamp <= {date_to}
+ AND {condition_filter}
+ )
+GROUP BY session_id
+HAVING last_seen <= {quiet_cutoff}
+ORDER BY last_seen DESC
+LIMIT {sample_count}
+"""
+
+
+def _sample_quiet_sessions(
+ team: Team,
+ condition_filter: ast.Expr | None,
+ sample_count: int,
+ date_from: datetime,
+ date_to: datetime,
+ quiet_cutoff: datetime,
+) -> list[str]:
+ with tags_context(product=Product.LLM_ANALYTICS):
+ response = query_ai_events(
+ query=parse_select(_SESSION_TEST_SAMPLE_SQL),
+ placeholders={
+ "date_from": ast.Constant(value=date_from),
+ "date_to": ast.Constant(value=date_to),
+ "quiet_cutoff": ast.Constant(value=quiet_cutoff),
+ "sample_count": ast.Constant(value=sample_count),
+ "condition_filter": condition_filter if condition_filter is not None else ast.Constant(value=True),
+ },
+ team=team,
+ query_type="EvaluationTestHogSessionSample",
+ fall_back_to_events=True,
+ )
+ return [str(row[0]) for row in (response.results or [])]
+
+
+def _session_io_preview(traces: list[LLMTrace]) -> tuple[str, str]:
+ """First input of the session's opening trace and last output of its closing one. The Hog body
+ still sees the whole session; this is only for display."""
+ input_preview = ""
+ output_preview = ""
+ for trace in traces:
+ for event in trace.events or []:
+ input_raw, output_raw = extract_event_io(event.event, event.properties)
+ if not input_preview:
+ input_preview = extract_text_from_messages(input_raw)[:200]
+ output_text = extract_text_from_messages(output_raw)[:200]
+ if output_text:
+ output_preview = output_text
+ return input_preview, output_preview
+
+
+def run_hog_eval_over_recent_sessions(
+ *,
+ team: Team,
+ bytecode: list[Any],
+ condition_filter: ast.Expr | None,
+ sample_count: int,
+ allows_na: bool,
+ quiet_period_seconds: int,
+ lookback_days: int = EVALUATION_TEST_LOOKBACK_DAYS,
+) -> list[SessionHogTestResult]:
+ """Sample sessions that have gone quiet and run session-level Hog bytecode against each.
+
+ The session mirror of `run_hog_eval_over_recent_traces`, so the editor preview matches how a
+ session evaluation runs online — whole session, session globals — rather than against one
+ generation or one trace. Each sampled session is fetched in full; `sample_count` is lower than
+ the trace path's because a session fetch is a whole conversation rather than a single trace.
+ """
+ now = datetime.now(UTC)
+ quiet_cutoff = now - timedelta(seconds=quiet_period_seconds)
+ date_from = now - timedelta(days=lookback_days)
+ session_ids = _sample_quiet_sessions(team, condition_filter, sample_count, date_from, now, quiet_cutoff)
+
+ results: list[SessionHogTestResult] = []
+ for session_id in session_ids:
+ outcome = fetch_session_for_evaluation(team.pk, session_id, now)
+ if outcome.skip_reason or outcome.traces is None:
+ results.append(
+ SessionHogTestResult(
+ session_id=session_id,
+ verdict=None,
+ reasoning="",
+ error=_SESSION_SKIP_REASONING.get(
+ outcome.skip_reason or "session_not_found", "Evaluation skipped."
+ ),
+ input_preview="",
+ output_preview="",
+ )
+ )
+ continue
+
+ globals_dict = build_session_hog_globals(outcome.traces, session_id, bytecode=bytecode)
+ hog_result = execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=allows_na)
+ input_preview, output_preview = _session_io_preview(outcome.traces)
+ results.append(
+ SessionHogTestResult(
+ session_id=session_id,
+ verdict=hog_result.get("verdict"),
+ reasoning=hog_result.get("reasoning") or "",
+ error=hog_result.get("error"),
+ input_preview=input_preview,
+ output_preview=output_preview,
+ )
+ )
+ return results
diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.py
index 8a43df2c3f6e..c9abfbeca37d 100644
--- a/posthog/temporal/ai_observability/run_trace_evaluation.py
+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py
@@ -34,15 +34,12 @@ 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_errors import is_terminal_user_error_result
from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io
from posthog.temporal.ai_observability.evaluation_hog import (
build_hog_event_global,
execute_hog_eval_bytecode,
+ finalize_hog_eval_result,
hog_bytecode_references_global,
)
from posthog.temporal.ai_observability.evaluation_llm_judge import (
@@ -50,6 +47,11 @@ from posthog.temporal.ai_observability.evaluation_llm_judge import (
call_llm_judge,
get_output_type_config,
)
+from posthog.temporal.ai_observability.evaluation_payload import (
+ PAYLOAD_BYTES_EXPR,
+ payload_budget_bytes,
+ should_skip_for_payload,
+)
from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
from posthog.temporal.ai_observability.evaluation_workflow_activities import (
EmitInternalTelemetryInputs,
@@ -175,6 +177,33 @@ def _count_trace_events(team: Team, trace_id: str, date_from: datetime, date_to:
return int(result.results[0][0])
+_TRACE_PAYLOAD_BYTES_SQL = f"""
+SELECT {PAYLOAD_BYTES_EXPR} AS payload_bytes
+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}}
+"""
+
+
+def _sum_trace_payload_bytes(team: Team, trace_id: str, date_from: datetime, date_to: datetime) -> int:
+ result = query_ai_events(
+ query=parse_select(_TRACE_PAYLOAD_BYTES_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="TraceEvaluationPayloadBytes",
+ fall_back_to_events=False,
+ )
+ if not result.results:
+ return 0
+ return int(result.results[0][0] or 0)
+
+
def _fetch_trace(team: Team, trace_id: str, date_from: datetime, date_to: datetime) -> TraceFetchOutcome:
"""Fetch a single full trace from ClickHouse over an explicit window, with a cheap count
preflight so degenerate traces are skipped before pulling their payload."""
@@ -184,6 +213,16 @@ def _fetch_trace(team: Team, trace_id: str, date_from: datetime, date_to: dateti
if event_count > MAX_TRACE_EVAL_EVENTS:
return TraceFetchOutcome(trace=None, skip_reason="trace_too_large", event_count=event_count)
+ # Log-only for trace. `should_skip_for_payload` returns False for this target by design: trace
+ # evaluations already run in production, and enforcing a brand-new dimension on them would start
+ # skipping units that grade fine today. The metric supplies the distribution needed to set a
+ # trace budget with evidence, and flipping it to enforcing is a deliberate follow-up.
+ should_skip_for_payload(
+ target="trace",
+ payload_bytes=_sum_trace_payload_bytes(team, trace_id, date_from, date_to),
+ budget_bytes=payload_budget_bytes(JUDGE_TRACE_MAX_CHARS),
+ )
+
runner = TraceQueryRunner(
team=team,
query=TraceQuery(
@@ -546,44 +585,7 @@ async def execute_trace_hog_eval_activity(inputs: ExecuteTraceEvaluationInputs)
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
+ return finalize_hog_eval_result(result, allows_na=allows_na, unit_label="trace")
@dataclass
@@ -595,6 +597,8 @@ class EmitTraceEvaluationEventInputs:
session_id: str | None
result: EvaluationActivityResult
start_time: datetime
+ target: str = "trace"
+ ai_session_id: str | None = None
@property
def properties_to_log(self) -> dict[str, Any]:
@@ -602,6 +606,7 @@ class EmitTraceEvaluationEventInputs:
"team_id": self.team_id,
"evaluation_id": self.evaluation.get("id"),
"trace_id": self.trace_id,
+ "target": self.target,
}
@@ -619,15 +624,28 @@ async def emit_trace_evaluation_event_activity(inputs: EmitTraceEvaluationEventI
# 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,
- }
- )
+ if inputs.target == "session" and inputs.ai_session_id:
+ properties.update(
+ {
+ "$ai_target_id": inputs.ai_session_id,
+ "$ai_target_type": "session_id",
+ # Makes the verdict session-scoped so the session view can read it. No
+ # $ai_trace_id: the verdict belongs to the session, not to any one trace, and
+ # inventing a trace id would make it render as that trace's verdict.
+ "$ai_session_id": inputs.ai_session_id,
+ "$session_id": inputs.session_id,
+ }
+ )
+ else:
+ 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,
diff --git a/posthog/temporal/ai_observability/test_evaluation_payload.py b/posthog/temporal/ai_observability/test_evaluation_payload.py
new file mode 100644
index 000000000000..d91f3bef6acb
--- /dev/null
+++ b/posthog/temporal/ai_observability/test_evaluation_payload.py
@@ -0,0 +1,37 @@
+import pytest
+
+from posthog.temporal.ai_observability.evaluation_payload import (
+ PAYLOAD_BYTES_EXPR,
+ payload_budget_bytes,
+ should_skip_for_payload,
+)
+
+
+class TestPayloadBudget:
+ def test_budget_tracks_the_targets_judge_budget(self):
+ assert payload_budget_bytes(500_000) > payload_budget_bytes(150_000)
+
+ def test_expression_covers_every_column_the_fetch_materializes(self):
+ """A column the fetch pulls but the sum omits is payload the cap cannot see, which is how
+ the event-count cap failed in the first place."""
+ for column in ("properties", "input", "output", "output_choices", "input_state", "output_state", "tools"):
+ assert column in PAYLOAD_BYTES_EXPR
+
+ @pytest.mark.parametrize(
+ "target,payload_bytes,budget_bytes,expected_skip",
+ [
+ # A session over budget is skipped: this is the case the event count cannot catch,
+ # since few-but-enormous events sit far under any row cap.
+ ("session", 5_000_000, 4_000_000, True),
+ ("session", 1_000, 4_000_000, False),
+ # Trace is measured but never skipped. Trace evaluations already run in production, so
+ # enforcing a new dimension on them would silently drop units that grade fine today.
+ ("trace", 5_000_000, 1_200_000, False),
+ ("trace", 1_000, 1_200_000, False),
+ ],
+ )
+ def test_session_enforces_and_trace_only_records(self, target, payload_bytes, budget_bytes, expected_skip):
+ assert (
+ should_skip_for_payload(target=target, payload_bytes=payload_bytes, budget_bytes=budget_bytes)
+ is expected_skip
+ )
diff --git a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
index 9a75ff06e277..e74c31b1b90c 100644
--- a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
@@ -15,12 +15,17 @@ from posthog.models import Organization, Team
from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
from posthog.temporal.ai_observability.evaluation_workflow_activities import RunEvaluationInputs
from posthog.temporal.ai_observability.run_aggregate_evaluation import (
+ MAX_SETTLE_POLLS_PER_RUN,
+ CheckSessionSettledInputs,
CheckTraceSettledInputs,
RunAggregateEvaluationInputs,
RunAggregateEvaluationWorkflow,
+ check_session_settled_activity,
check_trace_settled_activity,
+ resolve_poll_interval,
resolve_settle_plan,
)
+from posthog.temporal.ai_observability.run_session_evaluation import ExecuteSessionEvaluationInputs
from posthog.temporal.ai_observability.run_trace_evaluation import (
EmitTraceEvaluationEventInputs,
ExecuteTraceEvaluationInputs,
@@ -35,7 +40,13 @@ def setup_data():
def _insert_ai_event(
- *, team: Team, event: str, trace_id: str, arrival: datetime, event_timestamp: datetime | None = None
+ *,
+ team: Team,
+ event: str,
+ trace_id: str,
+ arrival: datetime,
+ event_timestamp: datetime | None = None,
+ session_id: str | None = None,
) -> None:
"""Insert a minimal ai_events row with `_timestamp` (arrival) set independently of
`timestamp` — the settle-poll activity judges liveness on `_timestamp`, not `timestamp`.
@@ -52,10 +63,10 @@ def _insert_ai_event(
"""
INSERT INTO sharded_ai_events (
uuid, event, timestamp, team_id, distinct_id, person_id, properties,
- trace_id, is_error, _timestamp, _offset, _partition
+ trace_id, session_id, is_error, _timestamp, _offset, _partition
) VALUES (
%(uuid)s, %(event)s, %(timestamp)s, %(team_id)s, %(distinct_id)s, %(person_id)s, %(properties)s,
- %(trace_id)s, 0, %(_timestamp)s, 0, 0
+ %(trace_id)s, %(session_id)s, 0, %(_timestamp)s, 0, 0
)
""",
{
@@ -67,6 +78,7 @@ def _insert_ai_event(
"person_id": str(uuid.uuid4()),
"properties": "{}",
"trace_id": trace_id,
+ "session_id": session_id,
"_timestamp": arrival.strftime("%Y-%m-%d %H:%M:%S"),
},
flush=False,
@@ -102,8 +114,59 @@ class TestResolveSettlePlan:
def test_resolves_and_clamps(self, settle, expected):
assert resolve_settle_plan(settle) == expected
+ @pytest.mark.parametrize(
+ "settle,expected",
+ [
+ # Absent strategy resolves to the session default, not the trace default.
+ (None, ("inactivity", 3600, 86400)),
+ ({}, ("inactivity", 3600, 86400)),
+ # Session-sized values survive; the trace ceilings would have crushed these to 1800/7200.
+ (
+ {"strategy": "inactivity", "quiet_period_seconds": 86400, "max_age_seconds": 604800},
+ ("inactivity", 86400, 604800),
+ ),
+ ({"strategy": "inactivity", "quiet_period_seconds": 3600}, ("inactivity", 3600, 86400)),
+ # Session ceilings still clamp above their own bounds.
+ ({"strategy": "inactivity", "quiet_period_seconds": 999999}, ("inactivity", 86400, 86400)),
+ ({"strategy": "inactivity", "max_age_seconds": 9999999}, ("inactivity", 3600, 604800)),
+ ({"strategy": "fixed_window", "window_seconds": 604800}, ("fixed_window", 604800, 604800)),
+ ({"strategy": "fixed_window", "window_seconds": 9999999}, ("fixed_window", 604800, 604800)),
+ ],
+ )
+ def test_resolves_and_clamps_for_session_target(self, settle, expected):
+ assert resolve_settle_plan(settle, "session") == expected
+
+
+class TestResolvePollInterval:
+ @pytest.mark.parametrize(
+ "primary_seconds,poll_budget_seconds,expected",
+ [
+ # Session defaults: a quarter of the quiet period, unchanged by the budget floor.
+ (3600, 82785, 900),
+ # The corner the floor exists for — quiet=10s with a 7-day max age. A quarter of the
+ # quiet period alone would be 10s, i.e. ~60k polls for one (evaluation, session).
+ (10, 604775, 605),
+ # Every in-bounds trace config must keep its old interval so in-flight trace runs
+ # replay with an unchanged retry policy. These are the trace extremes.
+ (10, 7175, 10),
+ (300, 6885, 75),
+ (1800, 5385, 450),
+ ],
+ )
+ def test_floors_the_cadence_on_the_budget_as_well_as_the_quiet_period(
+ self, primary_seconds, poll_budget_seconds, expected
+ ):
+ assert resolve_poll_interval(primary_seconds, poll_budget_seconds) == expected
+
+ def test_no_config_can_exceed_the_poll_ceiling(self):
+ for primary_seconds, poll_budget_seconds in [(10, 604775), (60, 604740), (10, 7175)]:
+ interval = resolve_poll_interval(primary_seconds, poll_budget_seconds)
+ assert poll_budget_seconds // interval <= MAX_SETTLE_POLLS_PER_RUN
+
+
+def _mock_activities(calls: list[str], exclude: set[str] | None = None) -> list[Any]:
+ exclude = exclude or set()
-def _mock_activities(calls: list[str]) -> list[Any]:
@activity.defn(name="fetch_evaluation_activity")
async def mock_fetch_evaluation(inputs: RunEvaluationInputs) -> dict[str, Any]:
calls.append("fetch")
@@ -132,18 +195,44 @@ def _mock_activities(calls: list[str]) -> list[Any]:
async def mock_telemetry(inputs: Any) -> None:
calls.append("telemetry")
- return [mock_fetch_evaluation, mock_execute_trace_hog, mock_emit, mock_telemetry]
+ @activity.defn(name="check_session_settled_activity")
+ async def mock_check_session_settled(inputs: CheckSessionSettledInputs) -> str:
+ calls.append("check_session_settled")
+ return "2026-07-23T00:00:00+00:00"
+ @activity.defn(name="execute_session_hog_eval_activity")
+ async def mock_execute_session_hog(inputs: ExecuteSessionEvaluationInputs) -> EvaluationActivityResult:
+ calls.append("execute_session")
+ return {"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False}
-def _workflow_inputs(settle: dict[str, Any]) -> RunAggregateEvaluationInputs:
- return RunAggregateEvaluationInputs(
- evaluation_id=str(uuid.uuid4()),
- team_id=1,
- trace_id="trace-123",
- distinct_id="user-1",
- session_id=None,
- settle=settle,
- )
+ @activity.defn(name="execute_session_llm_judge_activity")
+ async def mock_execute_session_judge(inputs: ExecuteSessionEvaluationInputs) -> EvaluationActivityResult:
+ calls.append("execute_session")
+ return {"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False}
+
+ all_activities = {
+ "fetch_evaluation_activity": mock_fetch_evaluation,
+ "execute_trace_hog_eval_activity": mock_execute_trace_hog,
+ "emit_trace_evaluation_event_activity": mock_emit,
+ "emit_internal_telemetry_activity": mock_telemetry,
+ "check_session_settled_activity": mock_check_session_settled,
+ "execute_session_hog_eval_activity": mock_execute_session_hog,
+ "execute_session_llm_judge_activity": mock_execute_session_judge,
+ }
+ return [fn for name, fn in all_activities.items() if name not in exclude]
+
+
+def _workflow_inputs(settle: dict[str, Any], **overrides: Any) -> RunAggregateEvaluationInputs:
+ defaults: dict[str, Any] = {
+ "evaluation_id": str(uuid.uuid4()),
+ "team_id": 1,
+ "trace_id": "trace-123",
+ "distinct_id": "user-1",
+ "session_id": None,
+ "settle": settle,
+ }
+ defaults.update(overrides)
+ return RunAggregateEvaluationInputs(**defaults)
class TestRunAggregateEvaluationWorkflow:
@@ -280,6 +369,107 @@ class TestRunAggregateEvaluationWorkflow:
assert elapsed >= timedelta(seconds=600)
assert elapsed < timedelta(seconds=750)
+ @pytest.mark.asyncio
+ async def test_session_target_polls_the_session_activity_and_evaluates(self):
+ calls: list[str] = []
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[RunAggregateEvaluationWorkflow],
+ activities=_mock_activities(calls),
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ result = await env.client.execute_workflow(
+ RunAggregateEvaluationWorkflow.run,
+ _workflow_inputs(
+ {"strategy": "inactivity", "quiet_period_seconds": 3600, "max_age_seconds": 86400},
+ target="session",
+ ai_session_id="session-abc",
+ ),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+ assert "check_session_settled" in calls
+ assert "check_trace_settled" not in calls
+ assert "execute_session" in calls
+ assert "execute" not in calls, "the trace execute activity must not run for a session target"
+ assert result["verdict"] is True
+
+ @pytest.mark.asyncio
+ async def test_session_still_active_at_max_age_grades_what_it_has(self):
+ """Guards the _is_still_not_settled error-type set: a hardcoded `trace_not_settled` match
+ would let this re-raise and fail the run instead of grading a partial session."""
+ calls: list[str] = []
+ task_queue = str(uuid.uuid4())
+
+ @activity.defn(name="check_session_settled_activity")
+ async def never_settles(inputs: CheckSessionSettledInputs) -> str:
+ calls.append("check_session_settled")
+ raise ApplicationError("session active 1s ago", type="session_not_settled")
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[RunAggregateEvaluationWorkflow],
+ activities=[*_mock_activities(calls, exclude={"check_session_settled_activity"}), never_settles],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ result = await env.client.execute_workflow(
+ RunAggregateEvaluationWorkflow.run,
+ _workflow_inputs(
+ {"strategy": "inactivity", "quiet_period_seconds": 60, "max_age_seconds": 300},
+ target="session",
+ ai_session_id="session-abc",
+ ),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+ assert result["verdict"] is True
+ assert "execute_session" in calls
+
+ @pytest.mark.asyncio
+ async def test_session_runaway_stops_polling_and_lets_the_fetch_report_it(self):
+ calls: list[str] = []
+ task_queue = str(uuid.uuid4())
+
+ @activity.defn(name="check_session_settled_activity")
+ async def runaway(inputs: CheckSessionSettledInputs) -> str:
+ calls.append("check_session_settled")
+ raise ApplicationError("session has 99999 events", type="session_runaway", non_retryable=True)
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[RunAggregateEvaluationWorkflow],
+ activities=[*_mock_activities(calls, exclude={"check_session_settled_activity"}), runaway],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ handle = await env.client.start_workflow(
+ RunAggregateEvaluationWorkflow.run,
+ _workflow_inputs(
+ {"strategy": "inactivity", "quiet_period_seconds": 60, "max_age_seconds": 86400},
+ target="session",
+ ai_session_id="session-abc",
+ ),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+ await handle.result()
+ # env.get_current_time() skews forward to the schedule-to-close timeout even once
+ # a non-retryable activity failure has already been delivered; the server-recorded
+ # execution window doesn't have that problem.
+ description = await handle.describe()
+ assert description.start_time is not None and description.close_time is not None
+ elapsed = description.close_time - description.start_time
+ assert calls.count("check_session_settled") == 1
+ assert "execute_session" in calls
+ # The point of the guard: it must not sit out the full 24h max_age first.
+ assert elapsed < timedelta(hours=1)
+
@freeze_time("2026-07-23T12:00:00Z")
class TestCheckTraceSettledActivity:
@@ -354,3 +544,137 @@ class TestCheckTraceSettledActivity:
# a client timestamp outside the lookback window used to make the row invisible to the poll.
assert err.value.type == "trace_not_settled"
assert "trace active" in err.value.message
+
+
+@freeze_time("2026-07-23T12:00:00Z")
+class TestCheckSessionSettledActivity:
+ @pytest.mark.django_db(transaction=True)
+ def test_settled_when_quiet_beyond_margin(self, setup_data):
+ team = setup_data["team"]
+ session_id = f"s-settled-{uuid.uuid4()}"
+ _insert_ai_event(
+ team=team,
+ event="$ai_generation",
+ trace_id=f"t-{uuid.uuid4()}",
+ arrival=datetime.now(UTC) - timedelta(seconds=60),
+ session_id=session_id,
+ )
+ result = check_session_settled_activity(
+ CheckSessionSettledInputs(
+ team_id=team.id, session_id=session_id, quiet_period_seconds=30, lookback_seconds=86400
+ )
+ )
+ assert result is not None
+
+ @pytest.mark.django_db(transaction=True)
+ def test_not_settled_while_activity_is_recent(self, setup_data):
+ team = setup_data["team"]
+ session_id = f"s-active-{uuid.uuid4()}"
+ _insert_ai_event(
+ team=team,
+ event="$ai_generation",
+ trace_id=f"t-{uuid.uuid4()}",
+ arrival=datetime.now(UTC),
+ session_id=session_id,
+ )
+ with pytest.raises(ApplicationError) as exc:
+ check_session_settled_activity(
+ CheckSessionSettledInputs(
+ team_id=team.id, session_id=session_id, quiet_period_seconds=300, lookback_seconds=86400
+ )
+ )
+ assert exc.value.type == "session_not_settled"
+
+ @pytest.mark.django_db(transaction=True)
+ def test_keeps_polling_when_nothing_is_visible(self, setup_data):
+ team = setup_data["team"]
+ with pytest.raises(ApplicationError) as exc:
+ check_session_settled_activity(
+ CheckSessionSettledInputs(
+ team_id=team.id,
+ session_id=f"s-missing-{uuid.uuid4()}",
+ quiet_period_seconds=30,
+ lookback_seconds=86400,
+ )
+ )
+ assert exc.value.type == "session_not_settled"
+ assert exc.value.non_retryable is False
+
+ @pytest.mark.django_db(transaction=True)
+ def test_events_carrying_another_session_id_do_not_count_as_activity(self, setup_data):
+ """Liveness must be scoped to the session, not the team."""
+ team = setup_data["team"]
+ session_id = f"s-quiet-{uuid.uuid4()}"
+ _insert_ai_event(
+ team=team,
+ event="$ai_generation",
+ trace_id=f"t-{uuid.uuid4()}",
+ arrival=datetime.now(UTC) - timedelta(seconds=60),
+ session_id=session_id,
+ )
+ _insert_ai_event(
+ team=team,
+ event="$ai_generation",
+ trace_id=f"t-{uuid.uuid4()}",
+ arrival=datetime.now(UTC),
+ session_id=f"s-other-{uuid.uuid4()}",
+ )
+ result = check_session_settled_activity(
+ CheckSessionSettledInputs(
+ team_id=team.id, session_id=session_id, quiet_period_seconds=30, lookback_seconds=86400
+ )
+ )
+ assert result is not None
+
+ @pytest.mark.django_db(transaction=True)
+ def test_evaluation_events_never_defer_settling(self, setup_data):
+ """Session verdicts now carry $ai_session_id, so two session evals would otherwise
+ defer each other's settling forever."""
+ team = setup_data["team"]
+ session_id = f"s-annotated-{uuid.uuid4()}"
+ _insert_ai_event(
+ team=team,
+ event="$ai_generation",
+ trace_id=f"t-{uuid.uuid4()}",
+ arrival=datetime.now(UTC) - timedelta(seconds=60),
+ session_id=session_id,
+ )
+ _insert_ai_event(
+ team=team,
+ event="$ai_evaluation",
+ trace_id="",
+ arrival=datetime.now(UTC),
+ session_id=session_id,
+ )
+ result = check_session_settled_activity(
+ CheckSessionSettledInputs(
+ team_id=team.id, session_id=session_id, quiet_period_seconds=30, lookback_seconds=86400
+ )
+ )
+ assert result is not None
+
+ @pytest.mark.django_db(transaction=True)
+ def test_over_cap_fails_fast_and_non_retryably(self, setup_data):
+ """A shared or constant $ai_session_id would otherwise poll for the full max_age."""
+ team = setup_data["team"]
+ session_id = f"s-huge-{uuid.uuid4()}"
+ for _ in range(3):
+ _insert_ai_event(
+ team=team,
+ event="$ai_generation",
+ trace_id=f"t-{uuid.uuid4()}",
+ arrival=datetime.now(UTC) - timedelta(seconds=60),
+ session_id=session_id,
+ )
+ with pytest.raises(ApplicationError) as exc:
+ check_session_settled_activity(
+ CheckSessionSettledInputs(
+ team_id=team.id,
+ session_id=session_id,
+ quiet_period_seconds=30,
+ lookback_seconds=86400,
+ runaway_events=2,
+ )
+ )
+ assert exc.value.type == "session_runaway"
+ assert exc.value.non_retryable is True
diff --git a/posthog/temporal/ai_observability/test_run_session_evaluation.py b/posthog/temporal/ai_observability/test_run_session_evaluation.py
new file mode 100644
index 000000000000..9db3d4f733e1
--- /dev/null
+++ b/posthog/temporal/ai_observability/test_run_session_evaluation.py
@@ -0,0 +1,468 @@
+import uuid
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import Mock, patch
+
+from asgiref.sync import async_to_sync
+from temporalio.exceptions import ApplicationError
+
+from posthog.schema import LLMTrace, LLMTraceEvent
+
+from posthog.hogql.constants import MAX_SELECT_TRACES_LIMIT_EXPORT
+
+from posthog.temporal.ai_observability.evaluation_payload import payload_budget_bytes
+from posthog.temporal.ai_observability.run_session_evaluation import (
+ _SESSION_EVENT_COUNT_SQL,
+ AI_EVENTS_RETENTION_DAYS,
+ JUDGE_SESSION_MAX_CHARS,
+ ExecuteSessionEvaluationInputs,
+ SessionFetchOutcome,
+ _count_session_events,
+ _SessionEventCount,
+ build_session_hog_globals,
+ execute_session_hog_eval_activity,
+ execute_session_llm_judge_activity,
+ fetch_session_for_evaluation,
+ format_session_for_judge,
+ session_fetch_lookback,
+)
+
+FROZEN_NOW = datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC)
+
+
+def _trace(
+ trace_id: str, *, cost: float, latency: float, event_count: int = 1, created_at: datetime | None = None
+) -> LLMTrace:
+ return LLMTrace.model_validate(
+ {
+ "id": trace_id,
+ "createdAt": (created_at or datetime.now(UTC)).isoformat(),
+ "distinctId": "person1",
+ "totalCost": cost,
+ "totalLatency": latency,
+ "events": [
+ LLMTraceEvent.model_validate(
+ {
+ "id": str(uuid.uuid4()),
+ "event": "$ai_generation",
+ "createdAt": datetime.now(UTC).isoformat(),
+ "properties": {
+ "$ai_input": [{"role": "user", "content": "hi"}],
+ "$ai_model": "gpt-4",
+ "$ai_latency": 0.5,
+ "$ai_total_cost_usd": 0.002,
+ },
+ }
+ )
+ for _ in range(event_count)
+ ],
+ }
+ )
+
+
+class TestSessionFetchLookback:
+ @pytest.mark.parametrize(
+ "max_age_seconds,expected",
+ [
+ # Never shorter than the trace lookback, so a short-window session still sees the
+ # events that arrived before its first matching generation.
+ (60, timedelta(hours=24)),
+ (86400, timedelta(hours=24)),
+ (7 * 24 * 3600, timedelta(days=7)),
+ ],
+ )
+ def test_covers_the_whole_settle_budget(self, max_age_seconds, expected):
+ assert session_fetch_lookback(max_age_seconds) == expected
+
+
+class TestBuildSessionHogGlobals:
+ def test_target_aggregates_across_traces(self):
+ traces = [_trace("t1", cost=1.5, latency=2.0), _trace("t2", cost=0.5, latency=3.0)]
+ globals_dict = build_session_hog_globals(traces, "s-1")
+ assert globals_dict["target"] == {
+ "type": "session",
+ "id": "s-1",
+ "total_cost_usd": 2.0,
+ "total_latency_seconds": 5.0,
+ }
+
+ def test_evaluation_events_span_every_trace(self):
+ traces = [_trace("t1", cost=0, latency=0, event_count=2), _trace("t2", cost=0, latency=0, event_count=3)]
+ globals_dict = build_session_hog_globals(traces, "s-1")
+ assert len(globals_dict["evaluation_events"]) == 5
+
+ def test_omits_the_trace_only_compatibility_globals(self):
+ """`events` and `trace` exist for saved trace-target Hog source. A session eval is new,
+ so building them would double the worker memory for nothing."""
+ globals_dict = build_session_hog_globals([_trace("t1", cost=0, latency=0)], "s-1")
+ assert "events" not in globals_dict
+ assert "trace" not in globals_dict
+
+ def test_only_builds_globals_the_bytecode_references(self):
+ traces = [_trace("t1", cost=0, latency=0)]
+ # Bytecode that reads `target` but not `evaluation_events`.
+ globals_dict = build_session_hog_globals(traces, "s-1", bytecode=["_H", 1, 32, "target", 1, 1])
+ assert "target" in globals_dict
+ assert "evaluation_events" not in globals_dict
+
+ def test_missing_costs_do_not_crash_the_aggregate(self):
+ trace = _trace("t1", cost=0, latency=0)
+ trace.totalCost = None
+ trace.totalLatency = None
+ globals_dict = build_session_hog_globals([trace], "s-1")
+ assert globals_dict["target"]["total_cost_usd"] == 0
+ assert globals_dict["target"]["total_latency_seconds"] == 0
+
+
+class TestFormatSessionForJudge:
+ def test_returns_none_rather_than_silently_dropping_trailing_traces(self):
+ # A final [:JUDGE_SESSION_MAX_CHARS] slice would drop the closing traces with no marker, so
+ # the caller must skip the session instead of judging a partial transcript.
+ traces = [_trace(f"t{i}", cost=0, latency=0, event_count=100) for i in range(260)]
+ assert format_session_for_judge(traces) is None
+
+ def test_many_small_traces_are_judged_rather_than_skipped_on_count_alone(self):
+ """The overflow check must measure the rendered transcript, not `per_trace_budget * n`.
+ The product form made this a hard cliff at 251 traces however little they contained, so a
+ long thin conversation was skipped while its content sat far inside the budget.
+ """
+ traces = [_trace(f"t{i}", cost=0, latency=0) for i in range(400)]
+ rendered = format_session_for_judge(traces)
+ assert rendered is not None
+ assert len(rendered) <= JUDGE_SESSION_MAX_CHARS
+ assert "t399" in rendered
+
+ def test_every_trace_appears(self):
+ traces = [_trace("t-alpha", cost=0, latency=0), _trace("t-beta", cost=0, latency=0)]
+ rendered = format_session_for_judge(traces)
+ assert rendered is not None
+ assert "t-alpha" in rendered
+ assert "t-beta" in rendered
+
+
+@freeze_time(FROZEN_NOW)
+class TestCountSessionEvents:
+ def test_the_count_stays_an_ungrouped_aggregate(self):
+ """An ungrouped aggregate always returns exactly one row, so `query_ai_events`'s
+ empty-result probe never fires and the stripped events-table fallback stays structurally
+ unreachable. A GROUP BY or HAVING would let the result come back empty for a session that
+ aged out of ai_events, which is what turns "expired" into a judge grading empty content.
+ """
+ normalized = " ".join(_SESSION_EVENT_COUNT_SQL.split()).upper()
+ assert "GROUP BY" not in normalized
+ assert "HAVING" not in normalized
+
+ def test_counts_the_rows_the_fetch_will_read_not_just_the_tagged_ones(self):
+ """`MAX_SESSION_EVAL_EVENTS` only bounds the payload if the preflight and
+ `SessionQueryRunner._build_query` select the same rows. The runner reads six event types and
+ resolves traces first, then reads every event of those traces — `session_id` is per-event and
+ nullable, so a producer that tags only the trace root would otherwise preflight at 1 while
+ the fetch reads the whole trace.
+ """
+ normalized = " ".join(_SESSION_EVENT_COUNT_SQL.split())
+ for event in ("$ai_span", "$ai_generation", "$ai_embedding", "$ai_metric", "$ai_feedback", "$ai_trace"):
+ assert f"'{event}'" in normalized
+ assert "trace_id IN (" in normalized
+ assert "session_id = {session_id}" in normalized
+
+ def test_never_falls_back_to_the_stripped_events_table(self):
+ first_seen = datetime(2026, 7, 1, tzinfo=UTC)
+ with patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.query_ai_events",
+ return_value=Mock(results=[[7, first_seen]]),
+ ) as mock_query_ai_events:
+ result = _count_session_events(Mock(), "s-1", datetime.now(UTC), datetime.now(UTC))
+
+ assert result.event_count == 7
+ assert result.first_seen == first_seen
+ assert mock_query_ai_events.call_args.kwargs["fall_back_to_events"] is False
+
+
+class TestFetchSessionForEvaluation:
+ def test_queries_in_evaluation_mode_with_both_date_bounds(self):
+ with (
+ patch("posthog.temporal.ai_observability.run_session_evaluation.Team"),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation._sum_session_payload_bytes",
+ return_value=0,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation._count_session_events",
+ return_value=_SessionEventCount(event_count=3, first_seen=datetime(2026, 7, 19, tzinfo=UTC)),
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.SessionQueryRunner"
+ ) as mock_session_query_runner,
+ ):
+ mock_session_query_runner.return_value.calculate.return_value = Mock(
+ results=[_trace("t1", cost=0, latency=0)], hasMore=False
+ )
+ fetch_session_for_evaluation(1, "s-1", datetime(2026, 7, 20, tzinfo=UTC))
+
+ kwargs = mock_session_query_runner.call_args.kwargs
+ assert kwargs["for_evaluation"] is True
+ assert kwargs["query"].dateRange.date_from is not None
+ assert kwargs["query"].dateRange.date_to is not None
+ # SessionQueryRunner defaults to 100 rows under LimitContext.QUERY, which would drop the
+ # tail of any session past 100 traces, so the fetch must ask for the export ceiling instead.
+ assert kwargs["query"].limit == MAX_SELECT_TRACES_LIMIT_EXPORT
+
+ def test_skips_a_small_session_whose_payload_is_enormous(self):
+ """The event count cannot see this: a handful of events carrying megabytes each sits far
+ under the row cap while being exactly the payload the cap exists to keep out of the worker.
+ """
+ with (
+ patch("posthog.temporal.ai_observability.run_session_evaluation.Team"),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation._count_session_events",
+ return_value=_SessionEventCount(event_count=14, first_seen=datetime(2026, 7, 19, tzinfo=UTC)),
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation._sum_session_payload_bytes",
+ return_value=payload_budget_bytes(JUDGE_SESSION_MAX_CHARS) + 1,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.SessionQueryRunner"
+ ) as mock_session_query_runner,
+ ):
+ outcome = fetch_session_for_evaluation(1, "s-1", datetime(2026, 7, 20, tzinfo=UTC))
+
+ assert outcome.skip_reason == "session_payload_too_large"
+ assert outcome.traces is None
+ mock_session_query_runner.assert_not_called()
+
+ def test_widens_date_from_to_the_sessions_real_start(self):
+ # A session that had been running for days before window_start must not have its opening
+ # cut just because a forward-looking budget (max_age) happened to be shorter than that.
+ first_seen = datetime(2026, 7, 10, tzinfo=UTC)
+ window_start = datetime(2026, 7, 20, tzinfo=UTC)
+ with (
+ patch("posthog.temporal.ai_observability.run_session_evaluation.Team"),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation._sum_session_payload_bytes",
+ return_value=0,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation._count_session_events",
+ return_value=_SessionEventCount(event_count=3, first_seen=first_seen),
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.SessionQueryRunner"
+ ) as mock_session_query_runner,
+ ):
+ mock_session_query_runner.return_value.calculate.return_value = Mock(
+ results=[_trace("t1", cost=0, latency=0)], hasMore=False
+ )
+ fetch_session_for_evaluation(1, "s-1", window_start)
+
+ query = mock_session_query_runner.call_args.kwargs["query"]
+ assert query.dateRange.date_from == first_seen.isoformat()
+
+ def test_floors_date_from_at_retention_for_a_session_older_than_retention(self):
+ # A session's real start is unreachable past ai_events retention regardless of the
+ # lookback math, so the fetch must not ask ClickHouse for data it can never return.
+ window_start = datetime(2026, 7, 20, tzinfo=UTC)
+ first_seen = window_start - timedelta(days=AI_EVENTS_RETENTION_DAYS + 10)
+ retention_floor = window_start - timedelta(days=AI_EVENTS_RETENTION_DAYS)
+ with (
+ patch("posthog.temporal.ai_observability.run_session_evaluation.Team"),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation._sum_session_payload_bytes",
+ return_value=0,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation._count_session_events",
+ return_value=_SessionEventCount(event_count=3, first_seen=first_seen),
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.SessionQueryRunner"
+ ) as mock_session_query_runner,
+ ):
+ mock_session_query_runner.return_value.calculate.return_value = Mock(
+ results=[_trace("t1", cost=0, latency=0)], hasMore=False
+ )
+ fetch_session_for_evaluation(1, "s-1", window_start)
+
+ query = mock_session_query_runner.call_args.kwargs["query"]
+ assert query.dateRange.date_from == retention_floor.isoformat()
+
+ def test_returns_traces_oldest_first_even_though_the_runner_orders_newest_first(self):
+ # SessionQueryRunner orders `first_timestamp DESC` for the UI session list. The judge's
+ # system prompt claims the traces it's handed are "in order", so the fetch must reverse
+ # that ordering rather than passing the DESC rows straight through.
+ oldest = _trace("t-oldest", cost=0, latency=0, created_at=datetime(2026, 7, 20, 9, tzinfo=UTC))
+ middle = _trace("t-middle", cost=0, latency=0, created_at=datetime(2026, 7, 20, 10, tzinfo=UTC))
+ newest = _trace("t-newest", cost=0, latency=0, created_at=datetime(2026, 7, 20, 11, tzinfo=UTC))
+ with (
+ patch("posthog.temporal.ai_observability.run_session_evaluation.Team"),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation._sum_session_payload_bytes",
+ return_value=0,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation._count_session_events",
+ return_value=_SessionEventCount(event_count=3, first_seen=datetime(2026, 7, 19, tzinfo=UTC)),
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.SessionQueryRunner"
+ ) as mock_session_query_runner,
+ ):
+ mock_session_query_runner.return_value.calculate.return_value = Mock(
+ results=[newest, middle, oldest], hasMore=False
+ )
+ outcome = fetch_session_for_evaluation(1, "s-1", datetime(2026, 7, 20, tzinfo=UTC))
+
+ assert outcome.traces is not None
+ assert [trace.id for trace in outcome.traces] == ["t-oldest", "t-middle", "t-newest"]
+
+ def test_treats_a_truncated_result_as_a_skip_rather_than_a_partial_grade(self):
+ with (
+ patch("posthog.temporal.ai_observability.run_session_evaluation.Team"),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation._sum_session_payload_bytes",
+ return_value=0,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation._count_session_events",
+ return_value=_SessionEventCount(event_count=3, first_seen=datetime(2026, 7, 19, tzinfo=UTC)),
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.SessionQueryRunner"
+ ) as mock_session_query_runner,
+ ):
+ mock_session_query_runner.return_value.calculate.return_value = Mock(
+ results=[_trace("t1", cost=0, latency=0)], hasMore=True
+ )
+ outcome = fetch_session_for_evaluation(1, "s-1", datetime(2026, 7, 20, tzinfo=UTC))
+
+ assert outcome.traces is None
+ assert outcome.skip_reason == "session_truncated"
+
+
+@freeze_time(FROZEN_NOW)
+class TestExecuteSessionActivities:
+ @pytest.mark.parametrize(
+ "skip_reason",
+ ["session_not_found", "session_too_large", "session_payload_too_large", "session_truncated"],
+ )
+ def test_hog_skips_carry_a_session_specific_reason(self, skip_reason):
+ with patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.fetch_session_for_evaluation",
+ return_value=SessionFetchOutcome(traces=None, skip_reason=skip_reason, event_count=0),
+ ):
+ result = async_to_sync(execute_session_hog_eval_activity)(
+ ExecuteSessionEvaluationInputs(
+ evaluation={
+ "evaluation_type": "hog",
+ "evaluation_config": {"bytecode": ["_H", 1, 32, True]},
+ "output_config": {"allows_na": False},
+ },
+ team_id=1,
+ session_id="s-1",
+ window_start=datetime.now(UTC).isoformat(),
+ )
+ )
+ assert result["skipped"] is True
+ assert result["skip_reason"] == skip_reason
+ assert "session" in result["reasoning"].lower()
+
+ def test_judge_rejects_a_non_judge_evaluation(self):
+ with pytest.raises(ApplicationError, match="Unsupported evaluation type"):
+ execute_session_llm_judge_activity(
+ ExecuteSessionEvaluationInputs(
+ evaluation={"evaluation_type": "hog", "output_type": "boolean"},
+ team_id=1,
+ session_id="s-1",
+ window_start=datetime.now(UTC).isoformat(),
+ )
+ )
+
+ def test_judge_skips_without_judging_when_the_session_is_truncated(self):
+ with (
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.fetch_session_for_evaluation",
+ return_value=SessionFetchOutcome(traces=None, skip_reason="session_truncated", event_count=0),
+ ),
+ patch("posthog.temporal.ai_observability.run_session_evaluation.call_llm_judge") as mock_call_llm_judge,
+ ):
+ result = execute_session_llm_judge_activity(
+ ExecuteSessionEvaluationInputs(
+ evaluation={
+ "evaluation_type": "llm_judge",
+ "evaluation_config": {"prompt": "Did the user accomplish their goal?"},
+ "output_type": "boolean",
+ "output_config": {"allows_na": False},
+ },
+ team_id=1,
+ session_id="s-1",
+ window_start=datetime.now(UTC).isoformat(),
+ )
+ )
+ assert result["skipped"] is True
+ assert result["skip_reason"] == "session_truncated"
+ # The whole point of the truncation-as-skip choice: never grade a partial transcript.
+ mock_call_llm_judge.assert_not_called()
+
+ def test_judge_skips_without_judging_when_the_rendered_transcript_would_overflow(self):
+ # The fetch itself succeeds (session_truncated wasn't raised there), but the session has
+ # enough traces that format_session_for_judge's char budget can't fit all of them. This is
+ # the overflow path the fetch-side truncation check above can't catch.
+ traces = [_trace(f"t{i}", cost=0, latency=0, event_count=100) for i in range(260)]
+ with (
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.fetch_session_for_evaluation",
+ return_value=SessionFetchOutcome(traces=traces, skip_reason=None, event_count=len(traces)),
+ ),
+ patch("posthog.temporal.ai_observability.run_session_evaluation.call_llm_judge") as mock_call_llm_judge,
+ ):
+ result = execute_session_llm_judge_activity(
+ ExecuteSessionEvaluationInputs(
+ evaluation={
+ "evaluation_type": "llm_judge",
+ "evaluation_config": {"prompt": "Did the user accomplish their goal?"},
+ "output_type": "boolean",
+ "output_config": {"allows_na": False},
+ },
+ team_id=1,
+ session_id="s-1",
+ window_start=datetime.now(UTC).isoformat(),
+ )
+ )
+ assert result["skipped"] is True
+ assert result["skip_reason"] == "session_too_long_to_judge"
+ mock_call_llm_judge.assert_not_called()
+
+ def test_our_bug_page_names_the_session_target(self):
+ unexpected_error = {
+ "verdict": None,
+ "reasoning": "",
+ "error": "Unexpected error during evaluation: KeyError: 'foo'",
+ "unexpected": True,
+ }
+ with (
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.fetch_session_for_evaluation",
+ return_value=SessionFetchOutcome(
+ traces=[_trace("t1", cost=0, latency=0)], skip_reason=None, event_count=1
+ ),
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.execute_hog_eval_bytecode",
+ return_value=unexpected_error,
+ ),
+ ):
+ with pytest.raises(ApplicationError, match=r"Hog evaluation error \(session\)"):
+ async_to_sync(execute_session_hog_eval_activity)(
+ ExecuteSessionEvaluationInputs(
+ evaluation={
+ "evaluation_type": "hog",
+ "evaluation_config": {"bytecode": ["_H", 1, 32, True]},
+ "output_config": {"allows_na": False},
+ },
+ team_id=1,
+ session_id="s-1",
+ window_start=datetime.now(UTC).isoformat(),
+ )
+ )
diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.py
index 8e7ced6eb2e0..d0ab1ea97287 100644
--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py
@@ -7,6 +7,8 @@ import pytest
from freezegun import freeze_time
from unittest.mock import MagicMock, patch
+from asgiref.sync import async_to_sync
+
from posthog.schema import LLMTrace, LLMTraceEvent
from posthog.hogql import ast
@@ -632,6 +634,90 @@ class TestEmitTraceEvaluationEventActivity:
await emit_trace_evaluation_event_activity(inputs)
+@freeze_time(FROZEN_NOW)
+class TestEmitSessionEvaluationEvent:
+ @pytest.mark.parametrize(
+ "target,ai_session_id,expected_target_type,expected_target_id",
+ [
+ ("trace", None, "trace_id", "trace-123"),
+ ("session", "session-abc", "session_id", "session-abc"),
+ ],
+ )
+ def test_target_linkage_per_target(
+ self,
+ target: str,
+ ai_session_id: str | None,
+ expected_target_type: str,
+ expected_target_id: str,
+ ) -> None:
+ captured: dict[str, Any] = {}
+
+ def _capture(**kwargs: Any) -> MagicMock:
+ captured.update(kwargs)
+ response = MagicMock()
+ response.raise_for_status.return_value = None
+ return response
+
+ with (
+ patch("posthog.temporal.ai_observability.run_trace_evaluation.capture_internal", side_effect=_capture),
+ patch("posthog.temporal.ai_observability.run_trace_evaluation.Team.objects.get", return_value=MagicMock()),
+ ):
+ async_to_sync(emit_trace_evaluation_event_activity)(
+ EmitTraceEvaluationEventInputs(
+ evaluation={"id": "eval-1", "name": "n", "output_type": "boolean"},
+ team_id=1,
+ trace_id="trace-123",
+ distinct_id="user-1",
+ session_id="ph-session-1",
+ result={"verdict": True, "reasoning": "", "result_type": "boolean"},
+ start_time=datetime.now(UTC),
+ target=target,
+ ai_session_id=ai_session_id,
+ )
+ )
+
+ props = captured["properties"]
+ assert props["$ai_target_type"] == expected_target_type
+ assert props["$ai_target_id"] == expected_target_id
+ # $session_id is the product-analytics session and is unrelated to $ai_session_id.
+ assert props["$session_id"] == "ph-session-1"
+ if ai_session_id is None:
+ assert "$ai_session_id" not in props
+ else:
+ assert props["$ai_session_id"] == ai_session_id
+
+ def test_session_verdict_carries_no_trace_id(self) -> None:
+ captured: dict[str, Any] = {}
+
+ def _capture(**kwargs: Any) -> MagicMock:
+ captured.update(kwargs)
+ response = MagicMock()
+ response.raise_for_status.return_value = None
+ return response
+
+ with (
+ patch("posthog.temporal.ai_observability.run_trace_evaluation.capture_internal", side_effect=_capture),
+ patch("posthog.temporal.ai_observability.run_trace_evaluation.Team.objects.get", return_value=MagicMock()),
+ ):
+ async_to_sync(emit_trace_evaluation_event_activity)(
+ EmitTraceEvaluationEventInputs(
+ evaluation={"id": "eval-1", "name": "n", "output_type": "boolean"},
+ team_id=1,
+ trace_id="trace-123",
+ distinct_id="user-1",
+ session_id=None,
+ result={"verdict": True, "reasoning": "", "result_type": "boolean"},
+ start_time=datetime.now(UTC),
+ target="session",
+ ai_session_id="session-abc",
+ )
+ )
+
+ props = captured["properties"]
+ assert "$ai_trace_id" not in props
+ assert props["$ai_session_id"] == "session-abc"
+
+
class TestRunTraceEvaluationWorkflowInputs:
def test_parse_inputs(self):
payload = {
diff --git a/products/ai_observability/backend/api/evaluation_reports.py b/products/ai_observability/backend/api/evaluation_reports.py
index 9bf4b8de5af2..39a7aa8e1e89 100644
--- a/products/ai_observability/backend/api/evaluation_reports.py
+++ b/products/ai_observability/backend/api/evaluation_reports.py
@@ -379,6 +379,10 @@ class EvaluationReportCitationSerializer(serializers.Serializer):
required=False,
help_text="Identifier of the trace cited by this report.",
)
+ session_id = serializers.CharField(
+ required=False,
+ help_text="Optional session identifier for session-target report citations.",
+ )
reason = serializers.CharField(
required=False,
help_text="Short explanation of why this example is cited.",
diff --git a/products/ai_observability/backend/api/evaluation_runs.py b/products/ai_observability/backend/api/evaluation_runs.py
index 77f3c9d66f21..4ecf9eb3c3c2 100644
--- a/products/ai_observability/backend/api/evaluation_runs.py
+++ b/products/ai_observability/backend/api/evaluation_runs.py
@@ -26,7 +26,7 @@ from posthog.temporal.common.client import sync_connect
from products.ai_observability.backend.api.metrics import llma_track_latency
-from ..models.evaluations import Evaluation
+from ..models.evaluations import Evaluation, EvaluationTarget
logger = structlog.get_logger(__name__)
@@ -88,6 +88,21 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
except Evaluation.DoesNotExist:
return Response({"error": f"Evaluation {evaluation_id} not found"}, status=404)
+ # This endpoint runs one $ai_generation through the generation workflow. Without this check
+ # a trace- or session-target evaluation is accepted and run as a generation, emitting a
+ # verdict with $ai_target_type "generation_uuid" under that evaluation's name — which then
+ # counts towards its pass rate while being invisible on the trace or session it belongs to.
+ if evaluation.target != EvaluationTarget.GENERATION.value:
+ return Response(
+ {
+ "error": (
+ f"This evaluation runs on the whole {evaluation.target}, so it can't be re-run against a "
+ "single generation."
+ )
+ },
+ status=400,
+ )
+
# Fetch event data from ClickHouse using available keys
where_clauses = [
"team_id = %(team_id)s",
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index 776c90ae23b9..6f84fe9f18b1 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -30,6 +30,7 @@ from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
from posthog.temporal.ai_observability.model_resolution import active_key_fallback
from posthog.temporal.ai_observability.run_evaluation import extract_event_io, run_hog_eval
+from posthog.temporal.ai_observability.run_session_evaluation import run_hog_eval_over_recent_sessions
from posthog.temporal.ai_observability.run_trace_evaluation import run_hog_eval_over_recent_traces
from ..hog import compile_ai_observability_hog
@@ -37,8 +38,14 @@ from ..llm import DEFAULT_MODEL_BY_PROVIDER
from ..models.evaluation_config import EvaluationConfig
from ..models.evaluation_configs import (
EVALUATION_TEST_LOOKBACK_DAYS,
- TRACE_EVAL_DEFAULT_MAX_AGE_SECONDS,
- TRACE_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
+ SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
+ SESSION_EVAL_MAX_MAX_AGE_SECONDS,
+ SESSION_EVAL_MAX_QUIET_PERIOD_SECONDS,
+ SESSION_EVAL_MAX_WINDOW_SECONDS,
+ SESSION_EVAL_MIN_MAX_AGE_SECONDS,
+ SESSION_EVAL_MIN_QUIET_PERIOD_SECONDS,
+ SESSION_EVAL_MIN_WINDOW_SECONDS,
+ SESSION_TEST_HOG_MAX_SAMPLES,
TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
TRACE_EVAL_MAX_MAX_AGE_SECONDS,
TRACE_EVAL_MAX_QUIET_PERIOD_SECONDS,
@@ -134,23 +141,25 @@ class _OutputConfigField(serializers.JSONField):
{
"type": "object",
"title": "Fixed window settle config",
+ "required": ["strategy"],
"properties": {
"strategy": {
"type": "string",
"enum": ["fixed_window"],
- "default": "fixed_window",
"description": "Wait a fixed window after the first matching generation, then evaluate.",
},
"window_seconds": {
"type": "integer",
"description": (
"Seconds to wait after the first matching generation before evaluating the whole "
- "trace. Captured when the run is scheduled — editing it does not change runs "
- "already in flight."
+ "unit. Captured when the run is scheduled — editing it does not change runs "
+ "already in flight. The accepted range depends on `target`: "
+ f"{TRACE_EVAL_MIN_WINDOW_SECONDS}–{TRACE_EVAL_MAX_WINDOW_SECONDS} for 'trace', "
+ f"{SESSION_EVAL_MIN_WINDOW_SECONDS}–{SESSION_EVAL_MAX_WINDOW_SECONDS} for 'session'. "
+ "The default also depends on `target`; see the field-level help_text."
),
- "minimum": TRACE_EVAL_MIN_WINDOW_SECONDS,
- "maximum": TRACE_EVAL_MAX_WINDOW_SECONDS,
- "default": TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
+ "minimum": min(TRACE_EVAL_MIN_WINDOW_SECONDS, SESSION_EVAL_MIN_WINDOW_SECONDS),
+ "maximum": max(TRACE_EVAL_MAX_WINDOW_SECONDS, SESSION_EVAL_MAX_WINDOW_SECONDS),
},
},
"additionalProperties": False,
@@ -163,24 +172,32 @@ class _OutputConfigField(serializers.JSONField):
"strategy": {
"type": "string",
"enum": ["inactivity"],
- "description": "Evaluate once the trace has had no new activity for the quiet period.",
+ "description": "Evaluate once the unit has had no new activity for the quiet period.",
},
"quiet_period_seconds": {
"type": "integer",
- "description": "Seconds without new trace activity before the trace counts as settled.",
- "minimum": TRACE_EVAL_MIN_QUIET_PERIOD_SECONDS,
- "maximum": TRACE_EVAL_MAX_QUIET_PERIOD_SECONDS,
- "default": TRACE_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
+ "description": (
+ "Seconds without new activity before the unit counts as settled. The accepted "
+ f"range depends on `target`: {TRACE_EVAL_MIN_QUIET_PERIOD_SECONDS}–"
+ f"{TRACE_EVAL_MAX_QUIET_PERIOD_SECONDS} for 'trace', "
+ f"{SESSION_EVAL_MIN_QUIET_PERIOD_SECONDS}–{SESSION_EVAL_MAX_QUIET_PERIOD_SECONDS} "
+ "for 'session'. The default also depends on `target`; see the field-level help_text."
+ ),
+ "minimum": min(TRACE_EVAL_MIN_QUIET_PERIOD_SECONDS, SESSION_EVAL_MIN_QUIET_PERIOD_SECONDS),
+ "maximum": max(TRACE_EVAL_MAX_QUIET_PERIOD_SECONDS, SESSION_EVAL_MAX_QUIET_PERIOD_SECONDS),
},
"max_age_seconds": {
"type": "integer",
"description": (
"Hard cap in seconds on the total wait from the first matching generation, even "
- "if the trace stays active. Must be at least quiet_period_seconds."
+ "if the unit stays active. Must be at least quiet_period_seconds. The accepted "
+ f"range depends on `target`: {TRACE_EVAL_MIN_MAX_AGE_SECONDS}–"
+ f"{TRACE_EVAL_MAX_MAX_AGE_SECONDS} for 'trace', "
+ f"{SESSION_EVAL_MIN_MAX_AGE_SECONDS}–{SESSION_EVAL_MAX_MAX_AGE_SECONDS} for 'session'. "
+ "The default also depends on `target`; see the field-level help_text."
),
- "minimum": TRACE_EVAL_MIN_MAX_AGE_SECONDS,
- "maximum": TRACE_EVAL_MAX_MAX_AGE_SECONDS,
- "default": TRACE_EVAL_DEFAULT_MAX_AGE_SECONDS,
+ "minimum": min(TRACE_EVAL_MIN_MAX_AGE_SECONDS, SESSION_EVAL_MIN_MAX_AGE_SECONDS),
+ "maximum": max(TRACE_EVAL_MAX_MAX_AGE_SECONDS, SESSION_EVAL_MAX_MAX_AGE_SECONDS),
},
},
"additionalProperties": False,
@@ -280,9 +297,11 @@ class EvaluationSerializer(serializers.ModelSerializer):
target_config = _TargetConfigField(
required=False,
help_text=(
- "Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — "
- "'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. "
- "Missing strategy means fixed_window. Empty for 'generation'."
+ "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on "
+ "`strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, "
+ "max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, "
+ "using per-target defaults, and the accepted bounds also depend on `target`. "
+ "Empty for 'generation'."
),
)
conditions = EvaluationConditionSerializer(
@@ -347,11 +366,13 @@ class EvaluationSerializer(serializers.ModelSerializer):
"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. When and how the trace run fires is "
- "controlled by target_config's settle strategy."
+ "individually. 'trace' evaluates the whole trace once and 'session' the whole "
+ "$ai_session_id session once: the first matching generation schedules a run that waits "
+ "for the unit to settle, then evaluates all of its events together. Condition filters "
+ "still match individual generations — a unit is evaluated when any of its generations "
+ "matches, and sampling applies per unit. A 'session' evaluation only fires for "
+ "generations that carry $ai_session_id. When and how the run fires is controlled by "
+ "target_config's settle strategy."
)
},
"deleted": {"help_text": "Set to true to soft-delete the evaluation."},
@@ -407,23 +428,30 @@ class EvaluationSerializer(serializers.ModelSerializer):
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.
+ # message index). An aggregate target emits a single evaluation event for the whole unit,
+ # where the message index is ambiguous and that per-generation linkage is absent.
+ # Aggregate-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:
+ if evaluation_type == EvaluationType.SENTIMENT.value and effective_target != EvaluationTarget.GENERATION.value:
raise serializers.ValidationError(
- {"target": "Sentiment evaluations can't target a whole trace. Use the 'generation' target."}
+ {"target": "Sentiment evaluations can only target each generation. Choose 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"
+ stored_target = getattr(self.instance, "target", None)
+ target = data.get("target") or stored_target or "generation"
config = data.get("target_config")
if config is None:
- config = getattr(self.instance, "target_config", {})
+ # Carrying the stored bag across a target change would keep the old target's
+ # strategy — a trace's fixed_window surviving onto a session means grading 30
+ # minutes into a conversation instead of when it goes quiet, which is exactly what
+ # DEFAULT_SETTLE_STRATEGY_BY_TARGET exists to prevent. Reseed instead, matching
+ # what the form does client-side.
+ config = {} if target != stored_target else getattr(self.instance, "target_config", {})
try:
data["target_config"] = validate_target_config(target, config or {})
except ValueError as e:
@@ -677,6 +705,16 @@ class TestHogTargetConfigSerializer(serializers.Serializer):
max_value=TRACE_EVAL_MAX_WINDOW_SECONDS,
help_text="Aggregation window for trace samples, in seconds.",
)
+ quiet_period_seconds = serializers.IntegerField(
+ required=False,
+ default=SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
+ min_value=SESSION_EVAL_MIN_QUIET_PERIOD_SECONDS,
+ max_value=SESSION_EVAL_MAX_QUIET_PERIOD_SECONDS,
+ help_text=(
+ "For session samples: only sessions with no activity for this long are previewed, "
+ "matching when a session evaluation would actually run."
+ ),
+ )
class TestHogRequestSerializer(serializers.Serializer):
@@ -707,8 +745,8 @@ class TestHogRequestSerializer(serializers.Serializer):
default=EvaluationTarget.GENERATION,
help_text=(
"What the evaluation runs against: 'generation' samples individual generations, "
- "'trace' samples whole traces and runs against trace-level globals — matching how the "
- "evaluation runs online."
+ "'trace' samples whole traces, and 'session' samples whole sessions that have gone "
+ "quiet. Each target runs against the same globals it would run against online."
),
)
target_config = TestHogTargetConfigSerializer(
@@ -722,14 +760,14 @@ class TestHogRequestSerializer(serializers.Serializer):
class TestHogResultItemSerializer(serializers.Serializer):
- sample_id = serializers.CharField(help_text="Stable identifier for the sampled generation or trace.")
+ sample_id = serializers.CharField(help_text="Stable identifier for the sampled generation, trace, or session.")
sample_type = serializers.ChoiceField(
choices=EvaluationTarget.choices,
- help_text="Type of sampled unit: generation or trace.",
+ help_text="Type of sampled unit: generation, trace, or session.",
)
event_uuid = serializers.CharField(
allow_null=True,
- help_text="UUID of the sampled $ai_generation event, or null for a trace sample.",
+ help_text="UUID of the sampled $ai_generation event, or null for a trace or session sample.",
)
trace_id = serializers.CharField(allow_null=True, help_text="Trace ID if available.")
input_preview = serializers.CharField(help_text="First 200 characters of input from the sampled unit.")
@@ -746,6 +784,87 @@ class TestHogResponseSerializer(serializers.Serializer):
)
+def _humanize_seconds(seconds: int) -> str:
+ """Whole units only: this reads back the quiet period the user just set, so "24 hours" beats
+ "1440 minutes"."""
+ if seconds >= 3600 and seconds % 3600 == 0:
+ hours = seconds // 3600
+ return f"{hours} hour" if hours == 1 else f"{hours} hours"
+ if seconds >= 60:
+ minutes = seconds // 60
+ return f"{minutes} minute" if minutes == 1 else f"{minutes} minutes"
+ return f"{seconds} second" if seconds == 1 else f"{seconds} seconds"
+
+
+def _test_hog_over_sessions(
+ *,
+ request: Request,
+ team: Team,
+ bytecode: list[Any],
+ condition_filter: ast.Expr | None,
+ sample_count: int,
+ allows_na: bool,
+ conditions: list[dict[str, Any]],
+ quiet_period_seconds: int,
+) -> Response:
+ """Session-target variant of `test_hog`: sample sessions that have gone quiet and run the code
+ against session-level globals, so the editor preview matches how a session eval runs online."""
+ tag_queries(product=Product.LLM_ANALYTICS, feature=Feature.QUERY)
+ try:
+ session_results = run_hog_eval_over_recent_sessions(
+ team=team,
+ bytecode=bytecode,
+ condition_filter=condition_filter,
+ sample_count=sample_count,
+ allows_na=allows_na,
+ quiet_period_seconds=quiet_period_seconds,
+ )
+ except AIEventsUnavailableError:
+ session_results = []
+
+ results = [
+ {
+ "sample_id": r.session_id,
+ "sample_type": EvaluationTarget.SESSION.value,
+ "event_uuid": None,
+ "trace_id": None,
+ "input_preview": r.input_preview,
+ "output_preview": r.output_preview,
+ "result": r.verdict,
+ "reasoning": r.reasoning,
+ "error": r.error,
+ }
+ for r in session_results
+ ]
+
+ report_user_action(
+ request.user,
+ "llma evaluation hog code tested",
+ {
+ "sample_count": sample_count,
+ "results_count": len(results),
+ "target": EvaluationTarget.SESSION.value,
+ "condition_count": len(conditions),
+ },
+ team=team,
+ )
+
+ if not results:
+ # An empty sample here is a real answer, not a failure: at a long quiet period there may
+ # genuinely be no settled session yet. Say which window came up empty so it does not
+ # read as broken.
+ return Response(
+ {
+ "results": [],
+ "message": (
+ f"No sessions have been quiet for {_humanize_seconds(quiet_period_seconds)} in the last "
+ f"{EVALUATION_TEST_LOOKBACK_DAYS} days, so there is nothing to preview yet."
+ ),
+ }
+ )
+ return Response({"results": results})
+
+
def _test_hog_over_traces(
*,
request: Request,
@@ -1042,6 +1161,20 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
elif condition_exprs:
condition_filter = ast.Or(exprs=condition_exprs)
+ if target == EvaluationTarget.SESSION.value:
+ return _test_hog_over_sessions(
+ request=request,
+ team=team,
+ bytecode=bytecode,
+ condition_filter=condition_filter,
+ sample_count=min(sample_count, SESSION_TEST_HOG_MAX_SAMPLES),
+ allows_na=allows_na,
+ conditions=conditions,
+ quiet_period_seconds=target_config.get(
+ "quiet_period_seconds", SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS
+ ),
+ )
+
if target == EvaluationTarget.TRACE.value:
return _test_hog_over_traces(
request=request,
diff --git a/products/ai_observability/backend/api/test/test_evaluation_reports.py b/products/ai_observability/backend/api/test/test_evaluation_reports.py
index 695513033b95..c2737e5f2325 100644
--- a/products/ai_observability/backend/api/test/test_evaluation_reports.py
+++ b/products/ai_observability/backend/api/test/test_evaluation_reports.py
@@ -241,6 +241,21 @@ class TestEvaluationReportApi(APIBaseTest):
evaluation.refresh_from_db()
return evaluation
+ def _create_session_evaluation(self) -> Evaluation:
+ return Evaluation.objects.create(
+ team=self.team,
+ name="Session Eval",
+ evaluation_type="llm_judge",
+ evaluation_config={"prompt": "test"},
+ output_type="boolean",
+ output_config={},
+ target=EvaluationTarget.SESSION,
+ target_config={"strategy": "inactivity", "quiet_period_seconds": 1800},
+ 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)
@@ -366,13 +381,14 @@ class TestEvaluationReportApi(APIBaseTest):
report = EvaluationReport.objects.get(evaluation=sentiment_evaluation)
self.assertEqual(response.json()["id"], str(report.id))
- def test_create_accepts_trace_evaluation(self) -> None:
- trace_evaluation = self._create_trace_evaluation()
+ @parameterized.expand([("trace",), ("session",)])
+ def test_create_accepts_aggregate_target_evaluation(self, target: str) -> None:
+ evaluation = self._create_trace_evaluation() if target == "trace" else self._create_session_evaluation()
response = self.client.post(
self.base_url,
{
- "evaluation": str(trace_evaluation.id),
+ "evaluation": str(evaluation.id),
"frequency": "every_n",
"trigger_threshold": 100,
"delivery_targets": [],
@@ -381,7 +397,7 @@ class TestEvaluationReportApi(APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
- report = EvaluationReport.objects.get(evaluation=trace_evaluation)
+ report = EvaluationReport.objects.get(evaluation=evaluation)
self.assertEqual(response.json()["id"], str(report.id))
@parameterized.expand([("trace_sentiment", "trace_sentiment"), ("unsupported_output", "unsupported")])
@@ -405,16 +421,17 @@ class TestEvaluationReportApi(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json().get("attr"), "evaluation")
- def test_deliverable_includes_supported_generation_and_trace_evaluations(self):
+ def test_deliverable_includes_every_reportable_target(self):
boolean_report = self._create_report()
sentiment_report = self._create_report(evaluation=self._create_sentiment_evaluation())
trace_report = self._create_report(evaluation=self._create_trace_evaluation())
+ session_report = self._create_report(evaluation=self._create_session_evaluation())
trace_sentiment_report = self._create_report(evaluation=self._create_trace_sentiment_evaluation())
unsupported_report = self._create_report(evaluation=self._create_unsupported_output_evaluation())
deliverable_ids = set(EvaluationReport.objects.deliverable().values_list("id", flat=True))
- self.assertEqual(deliverable_ids, {boolean_report.id, sentiment_report.id, trace_report.id})
+ self.assertEqual(deliverable_ids, {boolean_report.id, sentiment_report.id, trace_report.id, session_report.id})
self.assertNotIn(trace_sentiment_report.id, deliverable_ids)
self.assertNotIn(unsupported_report.id, deliverable_ids)
diff --git a/products/ai_observability/backend/api/test/test_evaluation_runs.py b/products/ai_observability/backend/api/test/test_evaluation_runs.py
index ba5118364d54..1233954b083b 100644
--- a/products/ai_observability/backend/api/test/test_evaluation_runs.py
+++ b/products/ai_observability/backend/api/test/test_evaluation_runs.py
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
from django.conf import settings
+from parameterized import parameterized
from rest_framework import status
from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags
@@ -170,6 +171,36 @@ class TestEvaluationRunViewSet(APIBaseTest):
assert response.status_code == status.HTTP_404_NOT_FOUND
+ @parameterized.expand(["trace", "session"])
+ def test_create_evaluation_run_refuses_aggregate_targets(self, target: str):
+ """This endpoint runs one generation through the generation workflow. Accepting an aggregate
+ target ran it as a generation and emitted a verdict with $ai_target_type 'generation_uuid'
+ under that evaluation's name, which counted towards its pass rate while being invisible on
+ the trace or session it belonged to."""
+ aggregate_evaluation = Evaluation.objects.create(
+ team=self.team,
+ name=f"{target} target",
+ evaluation_type="hog",
+ evaluation_config={"source": "return true"},
+ output_type="boolean",
+ output_config={},
+ target=target,
+ enabled=False,
+ )
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluation_runs/",
+ {
+ "evaluation_id": str(aggregate_evaluation.id),
+ "target_event_id": str(uuid.uuid4()),
+ "timestamp": datetime.now().isoformat(),
+ "event": "$ai_generation",
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert target in response.json()["error"]
+
def test_create_evaluation_run_missing_params(self):
"""Test creating evaluation run with missing parameters"""
response = self.client.post(
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index 97077168cd94..c61d280d9198 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -7,14 +7,16 @@ from unittest.mock import patch
from django.db import IntegrityError, transaction
from django.test import SimpleTestCase
+from drf_spectacular.plumbing import get_override
from parameterized import parameterized
from rest_framework import status
from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, HEAVY_COLUMN_TO_PROPERTY
from posthog.models import Organization, Project, Team, User
-from products.ai_observability.backend.api.evaluations import ModelConfigurationSerializer
+from products.ai_observability.backend.api.evaluations import ModelConfigurationSerializer, _TargetConfigField
from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
+from products.ai_observability.backend.models.evaluation_configs import validate_target_config
from products.ai_observability.backend.models.evaluation_reports import EvaluationReport
from products.ai_observability.backend.models.evaluations import Evaluation
from products.ai_observability.backend.models.model_configuration import LLMModelConfiguration
@@ -65,6 +67,30 @@ class TestModelConfigurationSerializer(SimpleTestCase):
self.assertEqual(serializer.errors[missing_field][0].code, "required")
+class TestTargetConfigFieldSchema(SimpleTestCase):
+ def test_every_oneof_branch_requires_the_discriminator(self) -> None:
+ """Orval only emits a discriminated zod union (one that picks a branch by `strategy` alone,
+ without matching optional fields against it) when every `oneOf` branch requires `strategy`.
+ A branch missing it lets Orval fall through to a plain `zod.union`, which previously let a
+ session payload sending only `{"strategy": "inactivity"}` match the fixed_window branch and
+ silently drop the inactivity fields.
+ """
+ schema = get_override(_TargetConfigField(), "field")
+ for branch in schema["oneOf"]:
+ self.assertIn("strategy", branch.get("required", []), branch["title"])
+
+ def test_no_branch_declares_a_default_for_a_shared_field(self) -> None:
+ """window_seconds/quiet_period_seconds/max_age_seconds have no single correct default: it
+ depends on `target`, which lives outside this schema. A `default` here would regenerate as
+ a zod `.default(...)` that materializes the wrong target's value before the request ever
+ reaches `validate_target_config`, which is exactly how session evals got trace timings.
+ """
+ schema = get_override(_TargetConfigField(), "field")
+ for branch in schema["oneOf"]:
+ for field_name, field_schema in branch["properties"].items():
+ self.assertNotIn("default", field_schema, f"{branch['title']}.{field_name}")
+
+
class TestEvaluationConfigsApi(APIBaseTest):
def _create_configured_llm_judge(self) -> tuple[Evaluation, LLMModelConfiguration]:
model_configuration = LLMModelConfiguration.objects.create(
@@ -179,6 +205,60 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(evaluation.target_config, {"strategy": "fixed_window", "window_seconds": 30 * 60})
self.assertEqual(EvaluationReport.objects.filter(evaluation=evaluation).count(), 1)
+ @parameterized.expand(
+ [
+ ("trace", "session", {"strategy": "inactivity", "quiet_period_seconds": 3600, "max_age_seconds": 86400}),
+ ("session", "trace", {"strategy": "fixed_window", "window_seconds": 1800}),
+ ]
+ )
+ def test_changing_target_reseeds_the_settle_config(self, from_target, to_target, expected):
+ evaluation = Evaluation.objects.create(
+ team=self.team,
+ name=f"switch {from_target} to {to_target}",
+ evaluation_type="hog",
+ evaluation_config={"source": "return true"},
+ output_type="boolean",
+ output_config={},
+ conditions=[],
+ target=from_target,
+ target_config=validate_target_config(from_target, {}),
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/", {"target": to_target}
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["target_config"], expected)
+
+ def test_changing_target_still_honors_an_explicit_settle_config(self):
+ evaluation = Evaluation.objects.create(
+ team=self.team,
+ name="switch with explicit config",
+ evaluation_type="hog",
+ evaluation_config={"source": "return true"},
+ output_type="boolean",
+ output_config={},
+ conditions=[],
+ target="trace",
+ target_config=validate_target_config("trace", {}),
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/",
+ {
+ "target": "session",
+ "target_config": {"strategy": "inactivity", "quiet_period_seconds": 120, "max_age_seconds": 3600},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ response.json()["target_config"],
+ {"strategy": "inactivity", "quiet_period_seconds": 120, "max_age_seconds": 3600},
+ )
+
def test_trace_target_accepts_custom_window(self):
response = self.client.post(
f"/api/environments/{self.team.id}/evaluations/",
@@ -324,7 +404,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
"output_type": "boolean",
"output_config": {},
"conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],
- "target": "session",
+ "target": "bogus",
},
)
@@ -396,6 +476,84 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(response.json()["attr"], "target")
self.assertEqual(Evaluation.objects.count(), 0)
+ def test_rejects_sentiment_evaluation_with_session_target(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/",
+ {
+ "name": "Session sentiment",
+ "evaluation_type": "sentiment",
+ "output_type": "sentiment",
+ "evaluation_config": {"source": "user_messages"},
+ "target": "session",
+ },
+ )
+ self.assertEqual(response.status_code, 400, response.json())
+ self.assertEqual(response.json()["attr"], "target")
+
+ def test_accepts_session_target_with_session_sized_settle_config(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/",
+ {
+ "name": "Session goal",
+ "evaluation_type": "hog",
+ "output_type": "boolean",
+ "evaluation_config": {"source": "return true"},
+ "target": "session",
+ "target_config": {
+ "strategy": "inactivity",
+ "quiet_period_seconds": 86400,
+ "max_age_seconds": 604800,
+ },
+ },
+ )
+ self.assertEqual(response.status_code, 201, response.json())
+ self.assertEqual(
+ response.json()["target_config"],
+ {"strategy": "inactivity", "quiet_period_seconds": 86400, "max_age_seconds": 604800},
+ )
+
+ def test_rejects_session_sized_settle_config_on_trace_target(self):
+ """The documented OpenAPI range is the union of both targets, so the server is the gate."""
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/",
+ {
+ "name": "Trace goal",
+ "evaluation_type": "hog",
+ "output_type": "boolean",
+ "evaluation_config": {"source": "return true"},
+ "target": "trace",
+ "target_config": {"strategy": "inactivity", "quiet_period_seconds": 86400},
+ },
+ )
+ self.assertEqual(response.status_code, 400, response.json())
+ self.assertEqual(response.json()["attr"], "target_config")
+
+ @parameterized.expand(["generation", "trace", "session"])
+ def test_test_hog_previews_every_target(self, target: str):
+ """Every target an evaluation can run on must also be previewable, or the editor can only
+ check the code for some of them."""
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/test_hog/",
+ {"source": "return true", "target": target},
+ )
+ self.assertEqual(response.status_code, 200, response.json())
+ self.assertIn("results", response.json())
+
+ def test_session_preview_says_why_a_sample_is_empty(self):
+ """An empty session sample is a real answer at a long quiet period, so the caller has to be
+ able to tell it apart from a broken preview."""
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/test_hog/",
+ {"source": "return true", "target": "session", "target_config": {"quiet_period_seconds": 86400}},
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200, response.json())
+ body = response.json()
+ self.assertEqual(body["results"], [])
+ # `message` is the key the trace and generation previews already use, so the editor
+ # renders every target's empty sample through one path.
+ self.assertIn("24 hours", body["message"])
+
def test_sentiment_evaluation_rejects_model_configuration(self):
response = self.client.post(
f"/api/environments/{self.team.id}/evaluations/",
diff --git a/products/ai_observability/backend/migrations/0033_evaluation_target_session.py b/products/ai_observability/backend/migrations/0033_evaluation_target_session.py
new file mode 100644
index 000000000000..0563f1e95ff0
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0033_evaluation_target_session.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.14 on 2026-07-30 09:41
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("ai_observability", "0032_dataset_versioning")]
+
+ operations = [
+ migrations.AlterField(
+ model_name="evaluation",
+ name="target",
+ field=models.CharField(
+ choices=[
+ ("generation", "Generation"),
+ ("trace", "Trace"),
+ ("session", "Session"),
+ ],
+ db_default="generation",
+ default="generation",
+ max_length=20,
+ ),
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index 4ca7ec089a5b..586c68314890 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0032_dataset_versioning
+0033_evaluation_target_session
diff --git a/products/ai_observability/backend/models/evaluation_configs.py b/products/ai_observability/backend/models/evaluation_configs.py
index d6fee708aed1..e372d7f3c000 100644
--- a/products/ai_observability/backend/models/evaluation_configs.py
+++ b/products/ai_observability/backend/models/evaluation_configs.py
@@ -84,6 +84,32 @@ TRACE_EVAL_DEFAULT_MAX_AGE_SECONDS = 2 * 60 * 60
TRACE_EVAL_MIN_MAX_AGE_SECONDS = 60
TRACE_EVAL_MAX_MAX_AGE_SECONDS = 2 * 60 * 60
+# Session-target bounds. Sessions are long and bursty (mean 2.66h, p99 duration 48h), and the
+# premature-settle rate barely improves past a day of quiet (23.6% at 5m, 2.1% at 24h), so the
+# ceilings are session-sized rather than trace-sized. The 7-day max_age ceiling stays well inside
+# ai_events retention (30 days) so a settled session is still fetchable.
+SESSION_EVAL_DEFAULT_WINDOW_SECONDS = 30 * 60
+SESSION_EVAL_MIN_WINDOW_SECONDS = 10
+SESSION_EVAL_MAX_WINDOW_SECONDS = 7 * 24 * 60 * 60
+
+SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS = 60 * 60
+SESSION_EVAL_MIN_QUIET_PERIOD_SECONDS = 10
+SESSION_EVAL_MAX_QUIET_PERIOD_SECONDS = 24 * 60 * 60
+
+SESSION_EVAL_DEFAULT_MAX_AGE_SECONDS = 24 * 60 * 60
+SESSION_EVAL_MIN_MAX_AGE_SECONDS = 60
+SESSION_EVAL_MAX_MAX_AGE_SECONDS = 7 * 24 * 60 * 60
+
+# Lives here rather than beside MAX_TRACE_EVAL_EVENTS (run_trace_evaluation.py) because both the
+# settle poll and the session fetch enforce it, and those two modules can't import each other.
+MAX_SESSION_EVAL_EVENTS = 2500
+
+# A session fetch is a whole conversation rather than one trace, so a preview samples fewer of them
+# than the trace path does — each sampled session can carry up to MAX_SESSION_EVAL_EVENTS events.
+# Shared so the editor endpoint and the Max tool hold the same bound. Fidelity per session is never
+# traded away: a previewed session is fetched exactly as the online evaluation would fetch it.
+SESSION_TEST_HOG_MAX_SAMPLES = 3
+
class FixedWindowSettleConfig(BaseModel):
"""Wait a fixed window after the first matching generation, then evaluate."""
@@ -130,22 +156,85 @@ SettleConfig = Annotated[FixedWindowSettleConfig | InactivitySettleConfig, Field
_SETTLE_CONFIG_ADAPTER: TypeAdapter[FixedWindowSettleConfig | InactivitySettleConfig] = TypeAdapter(SettleConfig)
+class SessionFixedWindowSettleConfig(BaseModel):
+ """Wait a fixed window after the first matching generation, then evaluate the session."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ strategy: Literal["fixed_window"] = "fixed_window"
+ window_seconds: int = Field(
+ default=SESSION_EVAL_DEFAULT_WINDOW_SECONDS,
+ ge=SESSION_EVAL_MIN_WINDOW_SECONDS,
+ le=SESSION_EVAL_MAX_WINDOW_SECONDS,
+ description="Seconds to wait after the first matching generation before evaluating.",
+ )
+
+
+class SessionInactivitySettleConfig(BaseModel):
+ """Evaluate once the session has had no new activity for the quiet period."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ strategy: Literal["inactivity"] = "inactivity"
+ quiet_period_seconds: int = Field(
+ default=SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
+ ge=SESSION_EVAL_MIN_QUIET_PERIOD_SECONDS,
+ le=SESSION_EVAL_MAX_QUIET_PERIOD_SECONDS,
+ description="Seconds without new session activity before the unit counts as settled.",
+ )
+ max_age_seconds: int = Field(
+ default=SESSION_EVAL_DEFAULT_MAX_AGE_SECONDS,
+ ge=SESSION_EVAL_MIN_MAX_AGE_SECONDS,
+ le=SESSION_EVAL_MAX_MAX_AGE_SECONDS,
+ description="Hard cap on the total wait from the first matching generation.",
+ )
+
+ @model_validator(mode="after")
+ def validate_max_age_covers_quiet_period(self) -> "SessionInactivitySettleConfig":
+ if self.max_age_seconds < self.quiet_period_seconds:
+ raise ValueError("max_age_seconds must be greater than or equal to quiet_period_seconds")
+ return self
+
+
+SessionSettleConfig = Annotated[
+ SessionFixedWindowSettleConfig | SessionInactivitySettleConfig, Field(discriminator="strategy")
+]
+
+_SESSION_SETTLE_CONFIG_ADAPTER: TypeAdapter[SessionFixedWindowSettleConfig | SessionInactivitySettleConfig] = (
+ TypeAdapter(SessionSettleConfig)
+)
+
+# Membership here is what makes a target an aggregate target. `validate_target_config` looks the
+# adapter up rather than checking a separate list of names, so the two can't drift apart.
+_SETTLE_CONFIG_ADAPTERS: dict[str, TypeAdapter[Any]] = {
+ "trace": _SETTLE_CONFIG_ADAPTER,
+ "session": _SESSION_SETTLE_CONFIG_ADAPTER,
+}
+
+# Traces default to fixed_window because rows saved before strategies existed have no `strategy`
+# key and meant exactly that. Sessions have no such legacy, and a fixed window measured from the
+# first matching generation is unrelated to when a session ends, so they default to inactivity.
+DEFAULT_SETTLE_STRATEGY_BY_TARGET: dict[str, str] = {"trace": "fixed_window", "session": "inactivity"}
+
+
def validate_target_config(target: str, target_config: dict) -> dict:
"""Validate target_config based on target.
- Trace targets carry a settle config discriminated on `strategy`; rows saved before
- strategies existed have no `strategy` key and mean fixed_window. Every other target
- (generation today) carries no config, so its bag is normalized to empty — this also
- strips a stale settle config if a user switches a trace eval back to generation.
+ Aggregate targets (trace, session) carry a settle config discriminated on `strategy`, with
+ per-target bounds. Trace rows saved before strategies existed have no `strategy` key and mean
+ fixed_window. Every other target (generation today) carries no config, so its bag is
+ normalized to empty — this also strips a stale settle config when a user switches an
+ aggregate eval back to generation.
"""
- if target != "trace":
+ adapter = _SETTLE_CONFIG_ADAPTERS.get(target)
+ if adapter is None:
return {}
try:
config = {**(target_config or {})}
- config.setdefault("strategy", "fixed_window")
- return _SETTLE_CONFIG_ADAPTER.validate_python(config).model_dump()
+ config.setdefault("strategy", DEFAULT_SETTLE_STRATEGY_BY_TARGET[target])
+ return adapter.validate_python(config).model_dump()
except Exception as e:
- raise ValueError(f"Invalid target_config for trace: {str(e)}") from e
+ raise ValueError(f"Invalid target_config for {target}: {str(e)}") from e
# Mapping: (evaluation_type, output_type) -> (evaluation_config_model, output_config_model)
@@ -162,9 +251,12 @@ EVALUATION_CONFIG_CONTENT_KEYS: dict[str, str] = {
}
REPORTABLE_OUTPUT_TYPES: tuple[str, ...] = (OutputType.BOOLEAN.value, OutputType.SENTIMENT.value)
+# Sentiment is generation-only (see the target check in the evaluations API), so the aggregate
+# targets report on boolean results alone.
REPORTABLE_OUTPUT_TYPES_BY_TARGET: dict[str, tuple[str, ...]] = {
"generation": REPORTABLE_OUTPUT_TYPES,
"trace": (OutputType.BOOLEAN.value,),
+ "session": (OutputType.BOOLEAN.value,),
}
diff --git a/products/ai_observability/backend/models/evaluations.py b/products/ai_observability/backend/models/evaluations.py
index 7fbef2d9a2a3..07d4b4d52ab8 100644
--- a/products/ai_observability/backend/models/evaluations.py
+++ b/products/ai_observability/backend/models/evaluations.py
@@ -50,6 +50,7 @@ class EvaluationQuerySet(models.QuerySet):
class EvaluationTarget(models.TextChoices):
GENERATION = "generation", "Generation"
TRACE = "trace", "Trace"
+ SESSION = "session", "Session"
class Evaluation(ModelActivityMixin, UUIDTModel):
diff --git a/products/ai_observability/backend/models/test/test_evaluation_configs.py b/products/ai_observability/backend/models/test/test_evaluation_configs.py
index 196e95bd9b5e..34c666c75da1 100644
--- a/products/ai_observability/backend/models/test/test_evaluation_configs.py
+++ b/products/ai_observability/backend/models/test/test_evaluation_configs.py
@@ -48,3 +48,54 @@ class TestValidateTargetConfig:
def test_generation_strips_config(self):
assert validate_target_config("generation", {"strategy": "inactivity"}) == {}
+
+
+class TestValidateSessionTargetConfig:
+ @pytest.mark.parametrize(
+ "config,expected",
+ [
+ # No strategy means inactivity for sessions, unlike traces. There are no legacy
+ # strategy-less session rows, so nothing needs fixed_window back-compat here.
+ ({}, {"strategy": "inactivity", "quiet_period_seconds": 3600, "max_age_seconds": 86400}),
+ (None, {"strategy": "inactivity", "quiet_period_seconds": 3600, "max_age_seconds": 86400}),
+ (
+ {"strategy": "inactivity", "quiet_period_seconds": 86400, "max_age_seconds": 604800},
+ {"strategy": "inactivity", "quiet_period_seconds": 86400, "max_age_seconds": 604800},
+ ),
+ (
+ {"strategy": "fixed_window", "window_seconds": 604800},
+ {"strategy": "fixed_window", "window_seconds": 604800},
+ ),
+ ],
+ )
+ def test_session_configs_normalize(self, config, expected):
+ assert validate_target_config("session", config) == expected
+
+ @pytest.mark.parametrize(
+ "config",
+ [
+ {"strategy": "inactivity", "quiet_period_seconds": 86401},
+ {"strategy": "inactivity", "max_age_seconds": 604801},
+ {"strategy": "inactivity", "quiet_period_seconds": 5},
+ {"strategy": "inactivity", "quiet_period_seconds": 7200, "max_age_seconds": 3600},
+ {"strategy": "fixed_window", "window_seconds": 604801},
+ {"strategy": "sliding"},
+ {"unknown_key": 1},
+ ],
+ )
+ def test_invalid_session_configs_rejected(self, config):
+ with pytest.raises(ValueError):
+ validate_target_config("session", config)
+
+ @pytest.mark.parametrize(
+ "target,config",
+ [
+ ("trace", {"strategy": "inactivity", "quiet_period_seconds": 86400}),
+ ("trace", {"strategy": "inactivity", "max_age_seconds": 604800}),
+ ("trace", {"strategy": "fixed_window", "window_seconds": 604800}),
+ ],
+ )
+ def test_session_sized_values_rejected_for_trace(self, target, config):
+ """The widened OpenAPI range lets a client send these; the server is the enforcement point."""
+ with pytest.raises(ValueError):
+ validate_target_config(target, config)
diff --git a/products/ai_observability/backend/test_hog_eval_examples.py b/products/ai_observability/backend/test_hog_eval_examples.py
index f1cffa1ed38d..206783bbed51 100644
--- a/products/ai_observability/backend/test_hog_eval_examples.py
+++ b/products/ai_observability/backend/test_hog_eval_examples.py
@@ -16,6 +16,7 @@ from posthog.schema import LLMTrace, LLMTraceEvent
from posthog.cdp.validation import compile_hog
from posthog.temporal.ai_observability.evaluation_hog import execute_hog_eval_bytecode
from posthog.temporal.ai_observability.run_evaluation import run_hog_eval
+from posthog.temporal.ai_observability.run_session_evaluation import build_session_hog_globals
from posthog.temporal.ai_observability.run_trace_evaluation import build_trace_hog_globals
EXAMPLES_PATH = Path(__file__).resolve().parents[1] / "frontend" / "evaluations" / "hogEvalExamples.json"
@@ -109,6 +110,29 @@ def _make_clean_trace_globals(bytecode: list[Any]) -> dict[str, Any]:
return build_trace_hog_globals(trace, "trace-123", bytecode=bytecode)
+def _make_clean_session_globals(bytecode: list[Any]) -> dict[str, Any]:
+ """Two traces, so an example that reasons over a whole conversation sees more than one turn."""
+ traces = [
+ LLMTrace(
+ id=f"trace-{index}",
+ createdAt=CLEAN_EVENT["timestamp"],
+ distinctId="test-user",
+ totalCost=0.01,
+ totalLatency=1.5,
+ events=[
+ LLMTraceEvent(
+ id=f"{CLEAN_EVENT['uuid']}-{index}",
+ event=CLEAN_EVENT["event"],
+ createdAt=CLEAN_EVENT["timestamp"],
+ properties=CLEAN_EVENT["properties"],
+ )
+ ],
+ )
+ for index in (1, 2)
+ ]
+ return build_session_hog_globals(traces, "session-123", bytecode=bytecode)
+
+
class TestHogEvalExamplesCompile:
@parameterized.expand(EXAMPLE_LABELS)
def test_compiles(self, label):
@@ -135,6 +159,17 @@ class TestHogEvalExamplesRun:
assert result["error"] is None, f"'{label}' errored for a trace: {result['error']}"
assert isinstance(result["verdict"], bool), f"'{label}' returned non-bool for a trace: {result['verdict']}"
+ @parameterized.expand(EXAMPLE_LABELS)
+ def test_returns_bool_without_error_for_session(self, label):
+ """A session builds only `target` and `evaluation_events` — no `events` or `trace`. An
+ example reaching for a trace-only global would come back undefined here rather than error,
+ so assert on the verdict type as well: that is what catches it."""
+ bytecode = compile_hog(_get_source(label), "destination")
+ result = execute_hog_eval_bytecode(bytecode, _make_clean_session_globals(bytecode), allows_na=False)
+
+ assert result["error"] is None, f"'{label}' errored for a session: {result['error']}"
+ assert isinstance(result["verdict"], bool), f"'{label}' returned non-bool for a session: {result['verdict']}"
+
class TestHogEvalExamplesBehavior:
@parameterized.expand(
diff --git a/products/ai_observability/backend/tools/run_hog_eval.py b/products/ai_observability/backend/tools/run_hog_eval.py
index 49870b74f239..308dad73d224 100644
--- a/products/ai_observability/backend/tools/run_hog_eval.py
+++ b/products/ai_observability/backend/tools/run_hog_eval.py
@@ -13,6 +13,10 @@ from posthog.sync import database_sync_to_async
from products.ai_observability.backend.hog import compile_ai_observability_hog
from products.ai_observability.backend.models.evaluation_configs import (
EVALUATION_TEST_LOOKBACK_DAYS,
+ SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
+ SESSION_EVAL_MAX_QUIET_PERIOD_SECONDS,
+ SESSION_EVAL_MIN_QUIET_PERIOD_SECONDS,
+ SESSION_TEST_HOG_MAX_SAMPLES,
TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
TRACE_EVAL_MAX_WINDOW_SECONDS,
TRACE_EVAL_MIN_WINDOW_SECONDS,
@@ -25,25 +29,60 @@ TOOL_DESCRIPTION = f"""Test Hog evaluation code against sample data from the las
Returns compilation errors if the code is invalid, or pass/fail/error results for each sample.
Set `target` to match how the evaluation will run: `generation` samples individual generations,
-`trace` samples whole traces and exposes trace-level globals. For traces, set `window_seconds`
-to the evaluation's aggregation window so the preview matches online behavior.
+`trace` samples whole traces, and `session` samples whole sessions that have gone quiet. For
+traces, set `window_seconds` to the evaluation's aggregation window; for sessions, set
+`quiet_period_seconds` to its quiet period, so the preview matches online behavior.
Write new evaluations using these globals:
- `evaluation_events` (array): the events under evaluation — one generation for a generation
- target, all events of the trace for a trace target. Each item has `uuid`, `event`, `timestamp`,
- serialized `input` and `output`, readable `input_text` and `output_text`, and `properties`
- without large input, output, and tool payloads.
-- `target` (object): the sampled unit's `type` ('generation' or 'trace'), `id`, `total_cost_usd`,
- and `total_latency_seconds`.
+ target, all events of the trace for a trace target, all events of every trace in the session
+ for a session target. Each item has `uuid`, `event`, `timestamp`, serialized `input` and
+ `output`, readable `input_text` and `output_text`, and `properties` without large input,
+ output, and tool payloads.
+- `target` (object): the sampled unit's `type` ('generation', 'trace', or 'session'), `id`,
+ `total_cost_usd`, and `total_latency_seconds`.
Saved evaluations can still use the generation-only compatibility globals `input`, `output`,
-`properties`, and `event`, but do not use them in new source that should also work for traces.
+`properties`, and `event`, but do not use them in new source that should also work for traces
+or sessions.
The code must return a boolean: `true` for pass, `false` for fail.
Use `print()` statements to output reasoning.
"""
+def _format_sample(
+ label: str,
+ unit_id: str,
+ verdict: bool | None,
+ error: str | None,
+ input_preview: str,
+ output_preview: str,
+ reasoning: str,
+) -> list[str]:
+ if error:
+ verdict_str = "ERROR"
+ elif verdict is True:
+ verdict_str = "PASS"
+ elif verdict is False:
+ verdict_str = "FAIL"
+ else:
+ verdict_str = "N/A"
+
+ lines = [
+ f"{label} {unit_id}:",
+ f" Input: {input_preview}",
+ f" Output: {output_preview}",
+ f" Result: {verdict_str}",
+ ]
+ if reasoning:
+ lines.append(f" Reasoning: {reasoning}")
+ if error:
+ lines.append(f" Error: {error}")
+ lines.append("")
+ return lines
+
+
class RunHogEvalTestArgs(BaseModel):
source: str = Field(description="Hog evaluation source code to compile and test")
sample_count: int = Field(
@@ -52,9 +91,12 @@ class RunHogEvalTestArgs(BaseModel):
le=5,
description="Number of recent samples to test against (1-5)",
)
- target: Literal["generation", "trace"] = Field(
+ target: Literal["generation", "trace", "session"] = Field(
default="generation",
- description="What to sample: 'generation' (individual generations) or 'trace' (whole traces)",
+ description=(
+ "What to sample: 'generation' (individual generations), 'trace' (whole traces), "
+ "or 'session' (whole sessions that have gone quiet)."
+ ),
)
window_seconds: int = Field(
default=TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
@@ -62,6 +104,12 @@ class RunHogEvalTestArgs(BaseModel):
le=TRACE_EVAL_MAX_WINDOW_SECONDS,
description="Aggregation window for trace samples, in seconds",
)
+ quiet_period_seconds: int = Field(
+ default=SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
+ ge=SESSION_EVAL_MIN_QUIET_PERIOD_SECONDS,
+ le=SESSION_EVAL_MAX_QUIET_PERIOD_SECONDS,
+ description="For session samples: how long a session must have been inactive to be previewed, in seconds",
+ )
class RunHogEvalTestTool(MaxTool):
@@ -76,8 +124,9 @@ class RunHogEvalTestTool(MaxTool):
self,
source: str,
sample_count: int = 3,
- target: Literal["generation", "trace"] = "generation",
+ target: Literal["generation", "trace", "session"] = "generation",
window_seconds: int = TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
+ quiet_period_seconds: int = SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
) -> tuple[str, Any]:
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
from posthog.temporal.ai_observability.run_evaluation import run_hog_eval
@@ -92,6 +141,9 @@ class RunHogEvalTestTool(MaxTool):
if target == "trace":
return await self._run_over_traces(bytecode, sample_count, window_seconds)
+ if target == "session":
+ return await self._run_over_sessions(bytecode, sample_count, quiet_period_seconds)
+
# Read from ai_events with native heavy columns so the Hog body still
# sees `event.properties.$ai_input` etc. Falls back to the events table
# when ai_events returns nothing (data beyond the retention window).
@@ -247,23 +299,41 @@ class RunHogEvalTestTool(MaxTool):
lines: list[str] = [f"Sampled {len(trace_results)} trace(s). Ran against trace-level globals.", ""]
for r in trace_results:
- if r.error:
- verdict_str = "ERROR"
- elif r.verdict is True:
- verdict_str = "PASS"
- elif r.verdict is False:
- verdict_str = "FAIL"
- else:
- verdict_str = "N/A"
+ lines.extend(
+ _format_sample("Trace", r.trace_id, r.verdict, r.error, r.input_preview, r.output_preview, r.reasoning)
+ )
- lines.append(f"Trace {r.trace_id}:")
- lines.append(f" Input: {r.input_preview}")
- lines.append(f" Output: {r.output_preview}")
- lines.append(f" Result: {verdict_str}")
- if r.reasoning:
- lines.append(f" Reasoning: {r.reasoning}")
- if r.error:
- lines.append(f" Error: {r.error}")
- lines.append("")
+ return ("\n".join(lines), None)
+
+ async def _run_over_sessions(
+ self, bytecode: list[Any], sample_count: int, quiet_period_seconds: int
+ ) -> tuple[str, Any]:
+ from posthog.temporal.ai_observability.run_session_evaluation import run_hog_eval_over_recent_sessions
+
+ session_results = await database_sync_to_async(run_hog_eval_over_recent_sessions)(
+ team=self._team,
+ bytecode=bytecode,
+ condition_filter=None,
+ # Same bound the editor endpoint applies: each sampled session is fetched in full, so
+ # the generic sample_count ceiling is far too high for whole conversations.
+ sample_count=min(sample_count, SESSION_TEST_HOG_MAX_SAMPLES),
+ allows_na=True,
+ quiet_period_seconds=quiet_period_seconds,
+ )
+ if not session_results:
+ return (
+ f"No sessions have been quiet for {quiet_period_seconds} seconds in the last "
+ f"{EVALUATION_TEST_LOOKBACK_DAYS} days. Shorten the quiet period, or ingest "
+ "$ai_generation events carrying $ai_session_id.",
+ None,
+ )
+
+ lines: list[str] = [f"Sampled {len(session_results)} session(s). Ran against session-level globals.", ""]
+ for s in session_results:
+ lines.extend(
+ _format_sample(
+ "Session", s.session_id, s.verdict, s.error, s.input_preview, s.output_preview, s.reasoning
+ )
+ )
return ("\n".join(lines), None)
diff --git a/products/ai_observability/frontend/AIObservabilitySessionScene.tsx b/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
index e76778441b55..65ce4f44429c 100644
--- a/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
@@ -43,6 +43,10 @@ const LLMASessionFeedbackDisplay = lazyWithRetry(() =>
import('./LLMASessionFeedbackDisplay').then((m) => ({ default: m.LLMASessionFeedbackDisplay }))
)
+const LLMASessionEvaluationsDisplay = lazyWithRetry(() =>
+ import('./LLMASessionEvaluationsDisplay').then((m) => ({ default: m.LLMASessionEvaluationsDisplay }))
+)
+
type TurnPhase = 'userThinking' | 'aiThinking' | 'complete'
export const scene: SceneExport = {
@@ -233,6 +237,9 @@ function SessionSceneWrapper({ showBreadcrumb = false }: { showBreadcrumb?: bool
<LLMASessionFeedbackDisplay sessionId={sessionId} />
</Suspense>
)}
+ <Suspense fallback={<Spinner />}>
+ <LLMASessionEvaluationsDisplay sessionId={sessionId} />
+ </Suspense>
</div>
<SummarizeAllButton
loading={summariesLoading}
diff --git a/products/ai_observability/frontend/LLMASessionEvaluationsDisplay.tsx b/products/ai_observability/frontend/LLMASessionEvaluationsDisplay.tsx
new file mode 100644
index 000000000000..9fd627ca2914
--- /dev/null
+++ b/products/ai_observability/frontend/LLMASessionEvaluationsDisplay.tsx
@@ -0,0 +1,40 @@
+import { useValues } from 'kea'
+
+import { LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { aiObservabilitySessionEvaluationsLogic } from './aiObservabilitySessionEvaluationsLogic'
+import { EvalTooltipContent, getEvalBadgeProps, getEvalSummaries } from './components/EvalResultBadges'
+
+interface LLMASessionEvaluationsDisplayProps {
+ sessionId: string
+}
+
+export function LLMASessionEvaluationsDisplay({ sessionId }: LLMASessionEvaluationsDisplayProps): JSX.Element | null {
+ const { sessionEvaluations } = useValues(aiObservabilitySessionEvaluationsLogic({ sessionId }))
+
+ // A session that resumes after being evaluated can be graded again; collapse to the newest
+ // verdict per evaluation so a stale tag never sits beside a fresh one. Same helper the trace
+ // and generation surfaces use, so the tooltip and badge read identically everywhere.
+ const summaries = getEvalSummaries(sessionEvaluations)
+
+ if (summaries.length === 0) {
+ return null
+ }
+
+ return (
+ <>
+ {summaries.map((summary) => {
+ const { type, icon, label } = getEvalBadgeProps(summary.latestRun)
+ return (
+ <Tooltip key={summary.latestRun.evaluation_id} title={<EvalTooltipContent {...summary} />}>
+ <span>
+ <LemonTag type={type} icon={icon} size="medium">
+ {label}
+ </LemonTag>
+ </span>
+ </Tooltip>
+ )
+ })}
+ </>
+ )
+}
diff --git a/products/ai_observability/frontend/aiObservabilitySessionEvaluationsLogic.test.ts b/products/ai_observability/frontend/aiObservabilitySessionEvaluationsLogic.test.ts
new file mode 100644
index 000000000000..855ab1def4ab
--- /dev/null
+++ b/products/ai_observability/frontend/aiObservabilitySessionEvaluationsLogic.test.ts
@@ -0,0 +1,94 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { aiObservabilitySessionEvaluationsLogic } from './aiObservabilitySessionEvaluationsLogic'
+
+// uuid, timestamp, evaluation_id, evaluation_name, generation_id, trace_id, result, reasoning,
+// applicable, evaluation_type, result_type, sentiment_label, sentiment_score, session_id, skipped
+const SESSION_VERDICT_ROW = [
+ 'run-1',
+ '2026-07-29T00:00:00Z',
+ 'eval-1',
+ 'Goal reached',
+ '',
+ '',
+ true,
+ 'The user got their answer',
+ true,
+ 'hog',
+ 'boolean',
+ null,
+ null,
+ 'ai-session-9',
+ false,
+]
+
+describe('aiObservabilitySessionEvaluationsLogic', () => {
+ let logic: ReturnType<typeof aiObservabilitySessionEvaluationsLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ post: {
+ '/api/environments/:team_id/query/:kind': () => [200, { results: [SESSION_VERDICT_ROW] }],
+ },
+ })
+ initKeaTests()
+ logic = aiObservabilitySessionEvaluationsLogic({ sessionId: 'ai-session-9' })
+ logic.mount()
+ })
+
+ // Session verdicts are the only ones with no $ai_trace_id, so this logic exists purely to read
+ // them by $ai_session_id through the shared query. Result mapping is mapEvaluationRunRow's job
+ // and is covered in utils.test.ts; deduping is getEvalSummaries' and is covered in
+ // EvalResultBadges.test.tsx. What is only testable here is the wiring.
+ it('reads session verdicts as ordinary evaluation runs', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.loadSessionEvaluations()
+ }).toFinishAllListeners()
+
+ expect(logic.values.sessionEvaluations).toHaveLength(1)
+ expect(logic.values.sessionEvaluations[0]).toMatchObject({
+ evaluation_id: 'eval-1',
+ evaluation_name: 'Goal reached',
+ session_id: 'ai-session-9',
+ result: true,
+ })
+ })
+
+ it('does not query when there is no session id', async () => {
+ const querySpy = jest.spyOn(api, 'queryHogQL')
+ try {
+ const empty = aiObservabilitySessionEvaluationsLogic({ sessionId: '' })
+ empty.mount()
+ querySpy.mockClear()
+
+ await expectLogic(empty, () => {
+ empty.actions.loadSessionEvaluations()
+ }).toFinishAllListeners()
+
+ expect(querySpy).not.toHaveBeenCalled()
+ expect(empty.values.sessionEvaluations).toEqual([])
+ } finally {
+ querySpy.mockRestore()
+ }
+ })
+
+ it('clears verdicts when the query fails', async () => {
+ useMocks({
+ post: {
+ '/api/environments/:team_id/query/:kind': () => [500, { error: 'nope' }],
+ },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.loadSessionEvaluations()
+ }).toFinishAllListeners()
+
+ expect(logic.values.sessionEvaluations).toEqual([])
+ expect(logic.values.sessionEvaluationsLoading).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/aiObservabilitySessionEvaluationsLogic.ts b/products/ai_observability/frontend/aiObservabilitySessionEvaluationsLogic.ts
new file mode 100644
index 000000000000..02564f0a57fc
--- /dev/null
+++ b/products/ai_observability/frontend/aiObservabilitySessionEvaluationsLogic.ts
@@ -0,0 +1,103 @@
+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'
+
+import type { EvaluationRun } from './evaluations/types'
+import { queryEvaluationRuns } from './utils'
+
+// Session verdicts land after the session settles, up to the 7-day session max age. This is
+// generously past both that and ai_events retention, and exists so the query prunes partitions at
+// all — without it every session page view scans the team's whole $ai_evaluation history.
+const SESSION_EVALUATION_LOOKBACK_DAYS = 90
+
+export interface SessionEvaluationsLogicProps {
+ sessionId: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface aiObservabilitySessionEvaluationsLogicValues {
+ sessionEvaluations: EvaluationRun[]
+ sessionEvaluationsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface aiObservabilitySessionEvaluationsLogicActions {
+ loadSessionEvaluations: () => {
+ value: true
+ }
+ loadSessionEvaluationsFailure: () => {
+ value: true
+ }
+ loadSessionEvaluationsSuccess: (evaluations: EvaluationRun[]) => {
+ evaluations: EvaluationRun[]
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface aiObservabilitySessionEvaluationsLogicMeta {
+ key: string
+}
+
+export type aiObservabilitySessionEvaluationsLogicType = MakeLogicType<
+ aiObservabilitySessionEvaluationsLogicValues,
+ aiObservabilitySessionEvaluationsLogicActions,
+ SessionEvaluationsLogicProps,
+ aiObservabilitySessionEvaluationsLogicMeta
+>
+
+export const aiObservabilitySessionEvaluationsLogic = kea<aiObservabilitySessionEvaluationsLogicType>([
+ path(['scenes', 'ai-observability', 'aiObservabilitySessionEvaluationsLogic']),
+ props({} as SessionEvaluationsLogicProps),
+ key((props) => props.sessionId),
+
+ actions({
+ loadSessionEvaluations: true,
+ loadSessionEvaluationsSuccess: (evaluations: EvaluationRun[]) => ({ evaluations }),
+ loadSessionEvaluationsFailure: true,
+ }),
+
+ reducers({
+ sessionEvaluations: [
+ [] as EvaluationRun[],
+ {
+ loadSessionEvaluationsSuccess: (_, { evaluations }) => evaluations,
+ loadSessionEvaluationsFailure: () => [],
+ },
+ ],
+ sessionEvaluationsLoading: [
+ false,
+ {
+ loadSessionEvaluations: () => true,
+ loadSessionEvaluationsSuccess: () => false,
+ loadSessionEvaluationsFailure: () => false,
+ },
+ ],
+ }),
+
+ listeners(({ actions, props }) => ({
+ loadSessionEvaluations: async () => {
+ const { sessionId } = props
+ if (!sessionId) {
+ actions.loadSessionEvaluationsFailure()
+ return
+ }
+
+ // Session verdicts carry no $ai_trace_id, so SessionQueryRunner's `trace_id != ''`
+ // filter drops them; they have to be read by $ai_session_id. Going through the shared
+ // query keeps the row shape, the result normalizer and the badge components identical
+ // to the trace and generation surfaces.
+ try {
+ const runs = await queryEvaluationRuns({
+ sessionId,
+ lookbackDays: SESSION_EVALUATION_LOOKBACK_DAYS,
+ })
+ actions.loadSessionEvaluationsSuccess(runs)
+ } catch (error) {
+ console.error('Error loading session evaluations:', error)
+ actions.loadSessionEvaluationsFailure()
+ }
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadSessionEvaluations()
+ }),
+])
diff --git a/products/ai_observability/frontend/components/EvalResultBadges.tsx b/products/ai_observability/frontend/components/EvalResultBadges.tsx
index 09d05b92f9e8..dad452d43534 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.tsx
@@ -46,7 +46,7 @@ export function scopeRunsToTarget(runs: EvaluationRun[], generationEventId?: str
: runs.filter((run) => !run.generation_id)
}
-function EvalTooltipContent({ latestRun, runCount }: EvalSummary): JSX.Element {
+export function EvalTooltipContent({ latestRun, runCount }: EvalSummary): JSX.Element {
return (
<div className="max-w-80 space-y-1">
<div className="font-semibold">{latestRun.evaluation_name}</div>
diff --git a/products/ai_observability/frontend/components/EvalsTabContent.tsx b/products/ai_observability/frontend/components/EvalsTabContent.tsx
index 29abe0ba0d0a..3ae571ef19e6 100644
--- a/products/ai_observability/frontend/components/EvalsTabContent.tsx
+++ b/products/ai_observability/frontend/components/EvalsTabContent.tsx
@@ -77,7 +77,7 @@ function EvalsTabContentInner({
</Link>
) : generationEvent && !evaluationsLoading && runnableEvaluations.length === 0 ? (
<span className="text-muted text-sm">
- No generation-target evaluations to run manually. Trace-target evaluations run
+ No generation-target evaluations to run manually. Trace and session evaluations run
automatically.
</span>
) : generationEvent ? (
diff --git a/products/ai_observability/frontend/components/EvaluationResultTag.tsx b/products/ai_observability/frontend/components/EvaluationResultTag.tsx
index 6b2aa3f78291..14499caee870 100644
--- a/products/ai_observability/frontend/components/EvaluationResultTag.tsx
+++ b/products/ai_observability/frontend/components/EvaluationResultTag.tsx
@@ -7,7 +7,7 @@ import { capitalize } from '../sentimentUtils'
type EvaluationResultLike = Pick<
EvaluationRun,
- 'status' | 'result' | 'result_type' | 'evaluation_type' | 'sentiment_label'
+ 'status' | 'result' | 'result_type' | 'evaluation_type' | 'sentiment_label' | 'skipped'
>
interface EvaluationResultDisplay {
@@ -34,6 +34,11 @@ export function getEvaluationResultDisplay(run: EvaluationResultLike): Evaluatio
if (run.status === 'running') {
return { type: 'primary', icon: <IconMinus />, label: 'Running', sortValue: -1 }
}
+ // Before the result checks: a skip still carries `result: false` when the evaluation disallows
+ // N/A, so reading the result first would report a session that was never graded as failing.
+ if (run.skipped) {
+ return { type: 'muted', icon: <IconMinus />, label: 'Skipped', sortValue: 0.4 }
+ }
if (isSentimentRun(run)) {
const sentimentLabel = (run.sentiment_label || 'unknown').toLowerCase()
const display = SENTIMENT_DISPLAY[sentimentLabel] ?? {
diff --git a/products/ai_observability/frontend/components/EvaluationRunTargetCell.tsx b/products/ai_observability/frontend/components/EvaluationRunTargetCell.tsx
index 8f644feddc21..6f5323c5b9af 100644
--- a/products/ai_observability/frontend/components/EvaluationRunTargetCell.tsx
+++ b/products/ai_observability/frontend/components/EvaluationRunTargetCell.tsx
@@ -10,11 +10,21 @@ import { sanitizeTraceUrlSearchParams } from '../utils'
// Generation-target runs link to the specific event in the trace; trace-target
// runs (no generation id) link to the whole trace. Both land on the Evaluations tab.
+// Session-target runs have no trace id at all and link to the session instead.
export function EvaluationRunTargetCell({ run }: { run: EvaluationRun }): JSX.Element {
const { searchParams } = useValues(router)
if (!run.trace_id) {
- return <span className="font-mono text-sm text-muted">—</span>
+ if (!run.session_id) {
+ return <span className="font-mono text-sm text-muted">—</span>
+ }
+ return (
+ <div className="font-mono text-sm">
+ <Link to={urls.aiObservabilitySession(run.session_id)} className="text-primary">
+ session {run.session_id.slice(0, 12)}...
+ </Link>
+ </div>
+ )
}
// No timestamp param on purpose: the run's timestamp can be long after the trace
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index cd88e64e5ce2..ea742594975a 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -44,6 +44,7 @@ import { EvaluationRunsTable } from './components/EvaluationRunsTable'
import { EvaluationTriggers } from './components/EvaluationTriggers'
import { EVALUATION_PASSED_HOGQL, EVALUATION_SUMMARY_MAX_RUNS } from './constants'
import {
+ evaluationOffersSessionTarget,
evaluationSupportsReports,
evaluationSupportsRunSummary,
evaluationTypeHasEditableCriteria,
@@ -52,6 +53,9 @@ import {
} from './evaluationCapabilities'
import { evaluationReportLogic } from './evaluationReportLogic'
import {
+ DEFAULT_SESSION_MAX_AGE_SECONDS,
+ DEFAULT_SESSION_QUIET_PERIOD_SECONDS,
+ DEFAULT_SESSION_WINDOW_SECONDS,
DEFAULT_TRACE_MAX_AGE_SECONDS,
DEFAULT_TRACE_QUIET_PERIOD_SECONDS,
DEFAULT_TRACE_WINDOW_SECONDS,
@@ -115,9 +119,14 @@ export function AIObservabilityEvaluation(): JSX.Element {
const isHog = evaluation.evaluation_type === 'hog'
const isSentiment = evaluation.evaluation_type === 'sentiment'
- const effectiveStrategy: EvaluationSettleStrategy = settlingStrategyEnabled
- ? (evaluation.target_config.strategy ?? 'fixed_window')
- : 'fixed_window'
+ const isAggregateTarget = evaluation.target === 'trace' || evaluation.target === 'session'
+ const isSessionTarget = evaluation.target === 'session'
+ const offersSessionTarget = evaluationOffersSessionTarget(evaluation, settlingStrategyEnabled)
+ // Read the stored strategy whether or not the flag is on. The flag gates the *picker*, not what
+ // the row contains: an API- or MCP-created session eval is inactivity, and forcing fixed_window
+ // here rendered a "wait 30 minutes" field holding a default the config never had.
+ const effectiveStrategy: EvaluationSettleStrategy =
+ evaluation.target_config.strategy ?? (isSessionTarget ? 'inactivity' : 'fixed_window')
const isReportableEvaluation = evaluationSupportsReports(evaluation)
const supportsRunSummary = evaluationSupportsRunSummary(evaluation)
const isBooleanOutput = isBooleanEvaluationOutput(evaluation.output_type)
@@ -474,16 +483,20 @@ export function AIObservabilityEvaluation(): JSX.Element {
Hog code
</Link>{' '}
against{' '}
- {evaluation.target === 'trace'
- ? 'the whole trace'
- : 'each generation'}
+ {isSessionTarget
+ ? 'the whole session'
+ : evaluation.target === 'trace'
+ ? 'the whole trace'
+ : 'each generation'}
. No LLM cost.
</>
) : (
`Use an LLM to evaluate ${
- evaluation.target === 'trace'
- ? 'the whole trace'
- : 'each generation'
+ isSessionTarget
+ ? 'the whole session'
+ : evaluation.target === 'trace'
+ ? 'the whole trace'
+ : 'each generation'
} against a natural-language prompt.`
)}
</p>
@@ -503,16 +516,26 @@ export function AIObservabilityEvaluation(): JSX.Element {
value: 'trace',
label: 'Whole trace',
},
+ ...(offersSessionTarget
+ ? [
+ {
+ value: 'session' as const,
+ label: 'Whole session',
+ },
+ ]
+ : []),
]}
fullWidth
/>
</Field>
<p className="text-muted text-sm -mt-2">
- {evaluation.target === 'trace'
- ? 'Runs once per trace on all of its events together, after it settles.'
- : 'Runs on each matching generation event individually, right after it is ingested.'}
+ {isSessionTarget
+ ? 'Runs once per session on every trace it contains, after the session settles. Only fires for events that carry an AI session id.'
+ : evaluation.target === 'trace'
+ ? 'Runs once per trace on all of its events together, after it settles.'
+ : 'Runs on each matching generation event individually, right after it is ingested.'}
</p>
- {evaluation.target === 'trace' && (
+ {isAggregateTarget && (
<>
{settlingStrategyEnabled && (
<Field name="settle_strategy" label="Evaluate when">
@@ -526,7 +549,9 @@ export function AIObservabilityEvaluation(): JSX.Element {
},
{
value: 'inactivity',
- label: 'The trace goes quiet',
+ label: isSessionTarget
+ ? 'The session goes quiet'
+ : 'The trace goes quiet',
},
]}
fullWidth
@@ -543,7 +568,9 @@ export function AIObservabilityEvaluation(): JSX.Element {
value={
evaluation.target_config
.window_seconds ??
- DEFAULT_TRACE_WINDOW_SECONDS
+ (isSessionTarget
+ ? DEFAULT_SESSION_WINDOW_SECONDS
+ : DEFAULT_TRACE_WINDOW_SECONDS)
}
onChange={(value) => {
if (
@@ -558,11 +585,9 @@ export function AIObservabilityEvaluation(): JSX.Element {
}}
/>
<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.
+ {isSessionTarget
+ ? "How long to wait after the first matching generation before pulling the whole session (10s to 7 days). Captured when the run is scheduled, so changing it won't affect runs already in flight."
+ : "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>
@@ -577,7 +602,9 @@ export function AIObservabilityEvaluation(): JSX.Element {
value={
evaluation.target_config
.quiet_period_seconds ??
- DEFAULT_TRACE_QUIET_PERIOD_SECONDS
+ (isSessionTarget
+ ? DEFAULT_SESSION_QUIET_PERIOD_SECONDS
+ : DEFAULT_TRACE_QUIET_PERIOD_SECONDS)
}
onChange={(value) =>
patchTargetConfig({
@@ -586,8 +613,9 @@ export function AIObservabilityEvaluation(): JSX.Element {
}
/>
<p className="text-muted text-xs">
- Evaluate once the trace has had no new
- activity for this long (10s–30m).
+ {isSessionTarget
+ ? 'Evaluate once the session has had no new activity for this long (10s to 24 hours). Sessions often pause for a while mid-conversation, so a longer quiet period means fewer verdicts on a session that was not finished.'
+ : 'Evaluate once the trace has had no new activity for this long (10s–30m).'}
</p>
</div>
</Field>
@@ -597,7 +625,9 @@ export function AIObservabilityEvaluation(): JSX.Element {
value={
evaluation.target_config
.max_age_seconds ??
- DEFAULT_TRACE_MAX_AGE_SECONDS
+ (isSessionTarget
+ ? DEFAULT_SESSION_MAX_AGE_SECONDS
+ : DEFAULT_TRACE_MAX_AGE_SECONDS)
}
onChange={(value) =>
patchTargetConfig({
@@ -606,8 +636,9 @@ export function AIObservabilityEvaluation(): JSX.Element {
}
/>
<p className="text-muted text-xs">
- Always evaluate once the trace is this
- old, even if it's still active (1m–2h).
+ {isSessionTarget
+ ? 'Always evaluate once the session is this old, even if it is still active (1m to 7 days).'
+ : "Always evaluate once the trace is this old, even if it's still active (1m–2h)."}
</p>
</div>
</Field>
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx
index 7aa96899e10f..80070606c6a6 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx
@@ -47,6 +47,7 @@ const HOG_EVAL_COMMON_GLOBAL_DEFINITIONS: readonly HogGlobalDefinition[] = [
description: {
generation: 'The event for the generation being evaluated.',
trace: 'Every event in the trace being evaluated.',
+ session: 'Every event in every trace in the session being evaluated, in order.',
},
fields: [
{ name: 'uuid', type: 'string', description: 'The event UUID.' },
@@ -77,6 +78,7 @@ const HOG_EVAL_COMMON_GLOBAL_DEFINITIONS: readonly HogGlobalDefinition[] = [
description: {
generation: 'Details about the generation being evaluated.',
trace: 'Details about the trace being evaluated.',
+ session: 'Details about the session being evaluated.',
},
fields: [
{
@@ -85,6 +87,7 @@ const HOG_EVAL_COMMON_GLOBAL_DEFINITIONS: readonly HogGlobalDefinition[] = [
description: {
generation: 'The target type: generation.',
trace: 'The target type: trace.',
+ session: 'The target type: session.',
},
},
{
@@ -93,6 +96,7 @@ const HOG_EVAL_COMMON_GLOBAL_DEFINITIONS: readonly HogGlobalDefinition[] = [
description: {
generation: 'The generation event UUID.',
trace: 'The trace ID.',
+ session: 'The session ID.',
},
},
{
@@ -101,6 +105,7 @@ const HOG_EVAL_COMMON_GLOBAL_DEFINITIONS: readonly HogGlobalDefinition[] = [
description: {
generation: 'The total cost for the generation in USD, when available.',
trace: 'The total cost for the trace in USD, when available.',
+ session: 'The total cost across every trace in the session in USD, when available.',
},
},
{
@@ -109,6 +114,8 @@ const HOG_EVAL_COMMON_GLOBAL_DEFINITIONS: readonly HogGlobalDefinition[] = [
description: {
generation: 'The total latency for the generation in seconds, when available.',
trace: 'The total latency for the trace in seconds, when available.',
+ session:
+ 'The latency of every trace in the session added up, in seconds. This is time spent on AI work, not how long the session lasted.',
},
},
],
@@ -140,6 +147,7 @@ function buildMonacoHogGlobals(target: EvaluationTarget): Record<string, MonacoH
const HOG_EVAL_COMMON_GLOBALS_BY_TARGET = {
generation: buildMonacoHogGlobals('generation'),
trace: buildMonacoHogGlobals('trace'),
+ session: buildMonacoHogGlobals('session'),
}
const HOG_EVAL_GLOBALS_BY_TARGET = {
@@ -173,10 +181,14 @@ const HOG_EVAL_GLOBALS_BY_TARGET = {
event_count: { type: 'number' },
},
},
+ // No compatibility globals: those exist for Hog source saved before `target` and
+ // `evaluation_events` landed, and no session-target source predates them. This mirrors
+ // build_session_hog_globals, which builds the shared globals and nothing else.
+ session: HOG_EVAL_COMMON_GLOBALS_BY_TARGET.session,
}
function HogTestResultsPanel(): JSX.Element | null {
- const { hogTestResults, hogTestResultsLoading } = useValues(llmEvaluationLogic)
+ const { hogTestResults, hogTestResultsLoading, hogTestMessage } = useValues(llmEvaluationLogic)
const { clearHogTestResults } = useActions(llmEvaluationLogic)
if (!hogTestResults && !hogTestResultsLoading) {
@@ -218,6 +230,7 @@ function HogTestResultsPanel(): JSX.Element | null {
Clear
</LemonButton>
</div>
+ {hogTestMessage && <div className="text-sm text-muted">{hogTestMessage}</div>}
<LemonTable<TestHogResultItemApi>
columns={[
{
@@ -315,6 +328,7 @@ export function EvaluationCodeEditor(): JSX.Element {
}
const source = evaluation.evaluation_config.source
+ const isSessionTarget = evaluation.target === 'session'
return (
<div className="space-y-4">
@@ -340,9 +354,11 @@ export function EvaluationCodeEditor(): JSX.Element {
<div className="flex items-center gap-2">
<Tooltip
title={
- evaluation.target === 'trace'
- ? 'Compile and run your code against up to 5 recent traces, the same way it runs online'
- : 'Compile and run your code against up to 5 recent generations matching your trigger filters'
+ isSessionTarget
+ ? 'Compile and run your code against up to 3 sessions that have gone quiet, the same way it runs online'
+ : evaluation.target === 'trace'
+ ? 'Compile and run your code against up to 5 recent traces, the same way it runs online'
+ : 'Compile and run your code against up to 5 recent generations matching your trigger filters'
}
>
<LemonButton
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx
index cb3895ea7cec..cf48647e56ee 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx
@@ -159,8 +159,25 @@ describe('EvaluationReportViewer', () => {
expectedUrl: '/ai-observability/traces/trace%255D%2528id',
expectedLabel: 'trace',
},
+ // The trace the agent read inside the session is kept on the citation, but the link is to
+ // the session — that's the unit the report is about.
+ {
+ name: 'session citation',
+ citedId: 'session-9',
+ citation: { session_id: 'session-9', trace_id: 'trace-inside', reason: 'example' },
+ expectedUrl: '/ai-observability/sessions/session-9',
+ expectedLabel: 'session-...',
+ },
+ // Colons are common in real session IDs and are safe in a path segment, so they stay linked.
+ {
+ name: 'session citation with colons',
+ citedId: 'session:group:16-16:81008d53',
+ citation: { session_id: 'session:group:16-16:81008d53', reason: 'example' },
+ expectedUrl: '/ai-observability/sessions/session:group:16-16:81008d53',
+ expectedLabel: 'session',
+ },
])(
- 'links a $name to the correct trace view',
+ 'links a $name to the correct destination',
({ citedId, citation, expectedUrl, expectedLabel, content, expectedPlainText }) => {
const reportRun = buildReportRun(buildMetrics({ pass_rate: 80 }))
reportRun.content.sections = [{ title: 'Finding', content: content ?? `See \`${citedId}\`.` }]
@@ -169,10 +186,33 @@ describe('EvaluationReportViewer', () => {
render(<EvaluationReportViewer reportRun={reportRun} compact />)
const markdown = document.querySelector('[data-testid="react-markdown"]')
- expect(markdown?.textContent).toContain(`[\`${expectedLabel}\`](${expectedUrl})`)
+ // Angle-bracketed destination so an opaque ID containing ")" can't truncate the link.
+ expect(markdown?.textContent).toContain(`[\`${expectedLabel}\`](<${expectedUrl}>)`)
if (expectedPlainText) {
expect(markdown?.textContent).toContain(expectedPlainText)
}
}
)
+
+ // $ai_session_id comes from ingestion, so it is attacker-controllable with the public project
+ // token. Escaping the link destination turns the rest of the ID into live Markdown in a report
+ // the team trusts — verified in a browser to render an external link and an image beacon.
+ it.each([
+ ['a closing paren', 'sess)1 [CLICK](https://evil.example.com)'],
+ ['an angle bracket', 'sess> ![beacon](https://evil.example.com/p.png)'],
+ ['a bracket', 'sess] and [more](https://evil.example.com)'],
+ ['a space', 'sess 1'],
+ ])('leaves a session ID containing %s unlinked', (_label, sessionId) => {
+ const reportRun = buildReportRun(buildMetrics({ pass_rate: 80 }))
+ reportRun.content.sections = [{ title: 'Finding', content: `See \`${sessionId}\`.` }]
+ reportRun.content.citations = [{ session_id: sessionId, reason: 'example' }]
+
+ render(<EvaluationReportViewer reportRun={reportRun} compact />)
+
+ const rendered = document.querySelector('[data-testid="react-markdown"]')?.textContent ?? ''
+ // No link is generated, so the ID keeps the backticks the section already had and
+ // CommonMark renders it as inert inline code rather than parsing the payload.
+ expect(rendered).not.toContain('/ai-observability/sessions/')
+ expect(rendered).toBe(`See \`${sessionId}\`.`)
+ })
})
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
index c4c0656897d0..24dfa1fc320e 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
@@ -26,9 +26,37 @@ import type {
// replacement rather than surviving around a link.
const SAFE_CITATION_LABEL_RE = /^[A-Za-z0-9._~-]{1,8}$/
-function citationLinkLabel(citedId: string, isGenerationCitation: boolean): string {
+function citationLinkLabel(citedId: string, fallbackLabel: string): string {
const preview = citedId.slice(0, 8)
- return SAFE_CITATION_LABEL_RE.test(preview) ? `${preview}...` : isGenerationCitation ? 'generation' : 'trace'
+ return SAFE_CITATION_LABEL_RE.test(preview) ? `${preview}...` : fallbackLabel
+}
+
+// $ai_session_id is caller-supplied through ingestion and urls.aiObservabilitySession interpolates
+// it into the path raw, so a ">" or ")" in it escapes the Markdown link destination and the rest of
+// the ID renders as attacker-controlled Markdown. Only link IDs that can't do that; anything else
+// stays plain text. Percent-encoding the session URL is the real fix, but that also has to teach
+// the session scene to decode, which is a routing change beyond this.
+const LINKABLE_SESSION_ID_RE = /^[A-Za-z0-9._~:@-]+$/
+
+// A citation names the unit that was evaluated: a session, a generation, or a trace. Session
+// citations may also carry the trace the agent read inside them, but the link goes to the session.
+function citationTarget(c: EvaluationReportCitation): { citedId: string; url: string; label: string } | null {
+ if (c.session_id) {
+ if (!LINKABLE_SESSION_ID_RE.test(c.session_id)) {
+ return null
+ }
+ return { citedId: c.session_id, url: urls.aiObservabilitySession(c.session_id), label: 'session' }
+ }
+ const citedId = c.generation_id || c.trace_id
+ const traceId = c.trace_id || c.generation_id
+ if (!citedId || !traceId) {
+ return null
+ }
+ return {
+ citedId,
+ url: urls.aiObservabilityTrace(traceId, c.generation_id && c.trace_id ? { event: c.generation_id } : undefined),
+ label: c.generation_id ? 'generation' : 'trace',
+ }
}
function linkifyCitations(content: string, citations: EvaluationReportCitation[]): string {
@@ -38,17 +66,15 @@ function linkifyCitations(content: string, citations: EvaluationReportCitation[]
const tokens: Array<{ token: string; link: string }> = []
let out = content
citations.forEach((c, idx) => {
- const citedId = c.generation_id || c.trace_id
- const traceId = c.trace_id || c.generation_id
- if (!citedId || !traceId) {
+ const target = citationTarget(c)
+ if (!target) {
return
}
+ const { citedId, url } = target
const token = `\0CITE${idx}\0`
- const url = urls.aiObservabilityTrace(
- traceId,
- c.generation_id && c.trace_id ? { event: c.generation_id } : undefined
- )
- const link = `[\`${citationLinkLabel(citedId, Boolean(c.generation_id))}\`](${url})`
+ // Angle-bracket destination: trace and session IDs are opaque and caller-supplied, and a
+ // bare ")" in one would otherwise close the destination early and hijack the rest of the link.
+ const link = `[\`${citationLinkLabel(citedId, target.label)}\`](<${url}>)`
const before = out
out = out.split(`\`${citedId}\``).join(token)
out = out.split(`<${citedId}>`).join(token)
diff --git a/products/ai_observability/frontend/evaluations/constants.ts b/products/ai_observability/frontend/evaluations/constants.ts
index 30fd2151fbaf..bb28ea5f0127 100644
--- a/products/ai_observability/frontend/evaluations/constants.ts
+++ b/products/ai_observability/frontend/evaluations/constants.ts
@@ -9,3 +9,10 @@ export const EVALUATION_SUMMARY_MAX_RUNS = 250
// JSONExtractString keeps the lookup on the properties_group_ai column and its bloom filter index.
// Same reasoning as the predicates in posthog/temporal/ai_observability/eval_reports/output_types.py.
export const EVALUATION_PASSED_HOGQL = "properties.$ai_evaluation_result = 'true'"
+
+// A skipped run was never graded, but an evaluation that disallows N/A still emits result=false
+// alongside skipped=true, so any count that doesn't exclude skips reads them as failures. Mirrors
+// _NOT_SKIPPED_PREDICATE in posthog/temporal/ai_observability/eval_reports/output_types.py, which
+// the report metrics already apply — without this the two surfaces disagree about the same runs.
+export const EVALUATION_NOT_SKIPPED_HOGQL =
+ "(isNull(properties.$ai_evaluation_skipped) OR properties.$ai_evaluation_skipped != 'true')"
diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
index 80036df8130b..5c70354423f7 100644
--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
@@ -1,4 +1,8 @@
-import { evaluationSupportsReports, evaluationSupportsRunSummary } from './evaluationCapabilities'
+import {
+ evaluationOffersSessionTarget,
+ evaluationSupportsReports,
+ evaluationSupportsRunSummary,
+} from './evaluationCapabilities'
import type { EvaluationOutputType, EvaluationTarget } from './types'
describe('evaluationCapabilities', () => {
@@ -7,8 +11,12 @@ describe('evaluationCapabilities', () => {
>([
['boolean', 'generation', true, true],
['sentiment', 'generation', true, false],
+ // Sentiment is generation-only, so the aggregate targets report on boolean alone.
+ // This pins the frontend twin of REPORTABLE_OUTPUT_TYPES_BY_TARGET.
['boolean', 'trace', true, false],
['sentiment', 'trace', false, false],
+ ['boolean', 'session', true, false],
+ ['sentiment', 'session', false, false],
])(
'supports the expected capabilities for %s %s evaluations',
(outputType, target, supportsReports, supportsSummary) => {
@@ -18,4 +26,19 @@ describe('evaluationCapabilities', () => {
expect(evaluationSupportsRunSummary(evaluation)).toBe(supportsSummary)
}
)
+
+ // An evaluation already targeting a session must keep the option listed even with the flag off,
+ // since the API and MCP can create one. Otherwise the picker renders the raw 'session' value.
+ it.each<[target: EvaluationTarget | null, settlingStrategyEnabled: boolean, offered: boolean]>([
+ ['generation', true, true],
+ ['generation', false, false],
+ ['trace', false, false],
+ ['session', false, true],
+ ['session', true, true],
+ [null, false, false],
+ ])('offers the session target for a %s evaluation when the flag is %s', (target, flagEnabled, offered) => {
+ const evaluation = target === null ? null : { target }
+
+ expect(evaluationOffersSessionTarget(evaluation, flagEnabled)).toBe(offered)
+ })
})
diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
index c6f43c2347ec..521ac45db68a 100644
--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
@@ -1,7 +1,12 @@
import type { LLMProviderKey } from '../settings/llmProviderKeysLogic'
import type { EvaluationConfig, EvaluationOutputType, EvaluationType, LLMJudgeEvaluation } from './types'
-const REPORTABLE_OUTPUT_TYPES: ReadonlySet<EvaluationOutputType> = new Set(['boolean', 'sentiment'])
+// Mirrors REPORTABLE_OUTPUT_TYPES_BY_TARGET in evaluation_configs.py — keep the two in step.
+const REPORTABLE_OUTPUT_TYPES_BY_TARGET: Record<string, ReadonlySet<EvaluationOutputType>> = {
+ generation: new Set(['boolean', 'sentiment']),
+ trace: new Set(['boolean']),
+ session: new Set(['boolean']),
+}
export function isBooleanEvaluationOutput(outputType: EvaluationOutputType | null | undefined): boolean {
return outputType === 'boolean'
@@ -10,10 +15,10 @@ export function isBooleanEvaluationOutput(outputType: EvaluationOutputType | nul
export function evaluationSupportsReports(
evaluation: Pick<EvaluationConfig, 'output_type' | 'target'> | null | undefined
): boolean {
- if (evaluation?.output_type == null || !REPORTABLE_OUTPUT_TYPES.has(evaluation.output_type)) {
+ if (evaluation?.output_type == null || evaluation.target == null) {
return false
}
- return evaluation.target === 'generation' || (evaluation.target === 'trace' && evaluation.output_type === 'boolean')
+ return REPORTABLE_OUTPUT_TYPES_BY_TARGET[evaluation.target]?.has(evaluation.output_type) ?? false
}
export function evaluationSupportsRunSummary(
@@ -26,6 +31,16 @@ export function evaluationTypeUsesModelConfiguration(evaluationType: EvaluationT
return evaluationType === 'llm_judge'
}
+// Sessions are creatable through the API and MCP regardless of the UI flag, so an evaluation that
+// already targets one must keep the option listed even for a flag-off user. Without it the picker
+// falls back to rendering the raw 'session' value, and saving would silently drop the target.
+export function evaluationOffersSessionTarget(
+ evaluation: Pick<EvaluationConfig, 'target'> | null | undefined,
+ settlingStrategyEnabled: boolean
+): boolean {
+ return settlingStrategyEnabled || evaluation?.target === 'session'
+}
+
export function isLLMJudgeEvaluation(
evaluation: EvaluationConfig | null | undefined
): evaluation is LLMJudgeEvaluation {
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index 4fe54dad569b..c94f12815bd7 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -462,6 +462,46 @@ return result`,
window_seconds: 900,
})
})
+
+ it('seeds inactivity defaults when switching to the session target', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setEvaluationTarget('session')
+ }).toMatchValues({
+ evaluation: expect.objectContaining({
+ target: 'session',
+ target_config: {
+ strategy: 'inactivity',
+ quiet_period_seconds: 3600,
+ max_age_seconds: 86400,
+ },
+ }),
+ })
+ })
+
+ it('reseeds with session defaults, not trace defaults, when switching strategy', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setEvaluationTarget('session')
+ logic.actions.setSettleStrategy('fixed_window')
+ logic.actions.setSettleStrategy('inactivity')
+ }).toMatchValues({
+ evaluation: expect.objectContaining({
+ target_config: {
+ strategy: 'inactivity',
+ quiet_period_seconds: 3600,
+ max_age_seconds: 86400,
+ },
+ }),
+ })
+ })
+
+ it('clears the settle bag when switching back to generation', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setEvaluationTarget('session')
+ logic.actions.setEvaluationTarget('generation')
+ }).toMatchValues({
+ evaluation: expect.objectContaining({ target: 'generation', target_config: {} }),
+ })
+ })
})
describe('selectors', () => {
@@ -1033,6 +1073,25 @@ return result`,
})
})
+ // An evaluation that disallows N/A emits result=false alongside skipped=true, so a
+ // session that was never graded would otherwise be counted and listed as a failure.
+ it('excludes skipped runs from the fail bucket', async () => {
+ const skippedRun: EvaluationRun = {
+ ...mockRuns[1],
+ id: 'run-skipped',
+ generation_id: 'gen-skipped',
+ result: false,
+ skipped: true,
+ }
+ logic.actions.loadEvaluationRunsSuccess([...mockRuns, skippedRun])
+ logic.actions.setEvaluationSummaryFilter('fail', 'all')
+
+ await expectLogic(logic).toMatchValues({
+ filteredEvaluationRuns: [expect.objectContaining({ id: 'run-2' })],
+ runsToSummarizeCount: 1,
+ })
+ })
+
it('excludes non-completed runs when filter is not all', async () => {
const runsWithFailed: EvaluationRun[] = [
...mockRuns,
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index 6a1bc2d85f78..cf33dc5f8b80 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -57,6 +57,36 @@ export const DEFAULT_TRACE_WINDOW_SECONDS = 30 * 60
export const DEFAULT_TRACE_QUIET_PERIOD_SECONDS = 5 * 60
export const DEFAULT_TRACE_MAX_AGE_SECONDS = 2 * 60 * 60
+export const DEFAULT_SESSION_WINDOW_SECONDS = 30 * 60
+export const DEFAULT_SESSION_QUIET_PERIOD_SECONDS = 60 * 60
+export const DEFAULT_SESSION_MAX_AGE_SECONDS = 24 * 60 * 60
+
+const AGGREGATE_TARGETS: EvaluationTarget[] = ['trace', 'session']
+
+function seedSettleConfig(target: EvaluationTarget, strategy: EvaluationSettleStrategy): EvaluationTargetConfig {
+ if (!AGGREGATE_TARGETS.includes(target)) {
+ return {}
+ }
+ const isSession = target === 'session'
+ if (strategy === 'inactivity') {
+ return {
+ strategy: 'inactivity',
+ quiet_period_seconds: isSession ? DEFAULT_SESSION_QUIET_PERIOD_SECONDS : DEFAULT_TRACE_QUIET_PERIOD_SECONDS,
+ max_age_seconds: isSession ? DEFAULT_SESSION_MAX_AGE_SECONDS : DEFAULT_TRACE_MAX_AGE_SECONDS,
+ }
+ }
+ return {
+ strategy: 'fixed_window',
+ window_seconds: isSession ? DEFAULT_SESSION_WINDOW_SECONDS : DEFAULT_TRACE_WINDOW_SECONDS,
+ }
+}
+
+// A fixed window measured from the first matching generation is unrelated to when a session ends,
+// so sessions open on inactivity. Traces keep fixed_window to match every stored config.
+function defaultStrategyForTarget(target: EvaluationTarget): EvaluationSettleStrategy {
+ return target === 'session' ? 'inactivity' : 'fixed_window'
+}
+
export const DEFAULT_HOG_SOURCE = getHogEvalExample('output_not_empty').source
const LEGACY_HOG_DEFAULT_SOURCES = [
@@ -119,20 +149,29 @@ function filterEvaluationRuns(runs: EvaluationRun[], filter: EvaluationSummaryFi
}
const completedRuns = runs.filter((r) => r.status === 'completed')
+ // A skipped run carries result=false when the evaluation disallows N/A, so it has to be
+ // excluded before the outcome is read or it lands in the fail bucket without being graded.
+ const gradedRuns = completedRuns.filter((r) => !r.skipped)
if (filter === 'pass') {
- return completedRuns.filter((r) => r.result === true)
+ return gradedRuns.filter((r) => r.result === true)
}
if (filter === 'fail') {
- return completedRuns.filter((r) => r.result === false)
+ return gradedRuns.filter((r) => r.result === false)
}
if (filter === 'na') {
- return completedRuns.filter((r) => r.result === null)
+ return gradedRuns.filter((r) => r.result === null)
}
return completedRuns.filter((r) => r.sentiment_label?.toLowerCase() === filter)
}
-function buildHogTestRequest(evaluation: HogEvaluation): TestHogRequestApi {
+type TestableHogEvaluation = HogEvaluation
+
+function isTestableHogEvaluation(evaluation: EvaluationConfig | null): evaluation is TestableHogEvaluation {
+ return evaluation?.evaluation_type === 'hog'
+}
+
+function buildHogTestRequest(evaluation: TestableHogEvaluation): TestHogRequestApi {
const request: TestHogRequestApi = {
source: evaluation.evaluation_config.source,
sample_count: 5,
@@ -147,6 +186,19 @@ function buildHogTestRequest(evaluation: HogEvaluation): TestHogRequestApi {
window_seconds: evaluation.target_config.window_seconds ?? DEFAULT_TRACE_WINDOW_SECONDS,
}
}
+ if (evaluation.target === 'session') {
+ // Preview against the settle duration this evaluation is actually configured with, so the
+ // sample only contains sessions it would already have graded. A fixed_window session
+ // settles a fixed time after its first matching generation; sampling on that same duration
+ // of inactivity is the conservative read of it — every session in the sample has certainly
+ // settled, though a still-active one that settled mid-conversation won't be sampled.
+ request.target_config = {
+ quiet_period_seconds:
+ evaluation.target_config.strategy === 'fixed_window'
+ ? (evaluation.target_config.window_seconds ?? DEFAULT_SESSION_WINDOW_SECONDS)
+ : (evaluation.target_config.quiet_period_seconds ?? DEFAULT_SESSION_QUIET_PERIOD_SECONDS),
+ }
+ }
return request
}
@@ -180,6 +232,7 @@ export interface llmEvaluationLogicValues {
filteredEvaluationRuns: EvaluationRun[]
formValid: boolean
hasUnsavedChanges: boolean
+ hogTestMessage: string | null
hogTestResults: TestHogResultItemApi[] | null
hogTestResultsLoading: boolean
isForceRefresh: boolean
@@ -336,6 +389,9 @@ export interface llmEvaluationLogicActions {
setHogSource: (source: string) => {
source: string
}
+ setHogTestMessage: (message: string | null) => {
+ message: string | null
+ }
setModelConfiguration: (modelConfiguration: ModelConfiguration | null) => {
modelConfiguration: ModelConfiguration | null
}
@@ -477,6 +533,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
// Hog test actions
clearHogTestResults: true,
+ setHogTestMessage: (message: string | null) => ({ message }),
// Evaluation summary actions
setEvaluationSummaryFilter: (filter: EvaluationSummaryFilter, previousFilter: EvaluationSummaryFilter) => ({
@@ -488,7 +545,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
trackSummarizeClicked: true,
}),
- loaders(({ props, values }) => ({
+ loaders(({ props, values, actions }) => ({
hogTestResults: [
null as TestHogResultItemApi[] | null,
{
@@ -498,7 +555,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
return null
}
const evaluation = values.evaluation
- if (!evaluation || evaluation.evaluation_type !== 'hog') {
+ if (!isTestableHogEvaluation(evaluation)) {
return null
}
@@ -511,7 +568,11 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
...result,
reasoning: result.reasoning ?? '',
}))
+ // An empty sample is a real answer, not a failure. Without the API's
+ // explanation the panel is just an empty table, which reads as broken.
+ actions.setHogTestMessage(results.length === 0 ? (response.message ?? null) : null)
} catch (e: unknown) {
+ actions.setHogTestMessage(null)
const message = e instanceof Error ? e.message : typeof e === 'string' ? e : 'Unknown error'
results = [
{
@@ -531,8 +592,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
breakpoint?.()
const currentEvaluation = values.evaluation
if (
- !currentEvaluation ||
- currentEvaluation.evaluation_type !== 'hog' ||
+ !isTestableHogEvaluation(currentEvaluation) ||
JSON.stringify(buildHogTestRequest(currentEvaluation)) !== requestFingerprint
) {
return null
@@ -665,12 +725,9 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
if (!state) {
return null
}
- // Seed a fixed-window settle config when switching to trace so the fields show a
- // sane default; clear the bag when switching back so we don't persist stale settings.
- const target_config: EvaluationTargetConfig =
- target === 'trace'
- ? { strategy: 'fixed_window', window_seconds: DEFAULT_TRACE_WINDOW_SECONDS }
- : {}
+ // Seed the target's default settle config so the fields show sane values;
+ // clear the bag for generation so we don't persist stale settings.
+ const target_config = seedSettleConfig(target, defaultStrategyForTarget(target))
if (
state.evaluation_type === 'hog' &&
LEGACY_HOG_DEFAULT_SOURCES.includes(state.evaluation_config.source)
@@ -685,20 +742,12 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
return { ...state, target, target_config }
},
setSettleStrategy: (state, { strategy }) => {
- if (!state || state.target !== 'trace') {
+ if (!state || !AGGREGATE_TARGETS.includes(state.target)) {
return state
}
// Full reseed rather than a patch: the two strategies carry disjoint fields and
// extra="forbid" on the backend rejects leftovers from the other one.
- const target_config: EvaluationTargetConfig =
- strategy === 'inactivity'
- ? {
- strategy: 'inactivity',
- quiet_period_seconds: DEFAULT_TRACE_QUIET_PERIOD_SECONDS,
- max_age_seconds: DEFAULT_TRACE_MAX_AGE_SECONDS,
- }
- : { strategy: 'fixed_window', window_seconds: DEFAULT_TRACE_WINDOW_SECONDS }
- return { ...state, target_config }
+ return { ...state, target_config: seedSettleConfig(state.target, strategy) }
},
patchTargetConfig: (state, { patch }) =>
state ? { ...state, target_config: { ...state.target_config, ...patch } } : null,
@@ -720,6 +769,14 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
patchTargetConfig: () => null,
setTriggerConditions: () => null,
},
+ hogTestMessage: [
+ null as string | null,
+ {
+ setHogTestMessage: (_, { message }) => message,
+ clearHogTestResults: () => null,
+ testHogOnSample: () => null,
+ },
+ ],
selectedModel: [
'' as string,
{
diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.ts
index 160c15d39ae3..377df041429e 100644
--- a/products/ai_observability/frontend/evaluations/types.ts
+++ b/products/ai_observability/frontend/evaluations/types.ts
@@ -10,7 +10,7 @@ import type {
import { LLMProvider } from '../settings/llmProviderKeysLogic'
export type EvaluationType = 'llm_judge' | 'hog' | 'sentiment'
-export type EvaluationTarget = 'generation' | 'trace'
+export type EvaluationTarget = 'generation' | 'trace' | 'session'
export type EvaluationSettleStrategy = 'fixed_window' | 'inactivity'
export type EvaluationOutputType = 'boolean' | 'sentiment'
export type EvaluationStatus = 'active' | 'paused' | 'error'
@@ -36,13 +36,15 @@ export interface EvaluationOutputConfig {
allows_na?: boolean
}
-/** Settle config for aggregate targets. Rows saved before strategies existed have no
- * `strategy` key and mean 'fixed_window'. */
+/** Settle config for aggregate targets (trace, session). A missing `strategy` resolves per target:
+ * 'fixed_window' for a trace, because rows saved before strategies existed mean exactly that, and
+ * 'inactivity' for a session, which has no such rows. Accepted ranges also differ per target, both
+ * enforced by the backend's `validate_target_config`. */
export interface EvaluationTargetConfig {
strategy?: EvaluationSettleStrategy
/** fixed_window: seconds to wait after the first matching generation before evaluating. */
window_seconds?: number
- /** inactivity: seconds without new trace activity before the trace counts as settled. */
+ /** inactivity: seconds without new activity before the target counts as settled. */
quiet_period_seconds?: number
/** inactivity: hard cap in seconds on the total wait from the first matching generation. */
max_age_seconds?: number
@@ -122,6 +124,9 @@ export interface EvaluationRun {
evaluation_name: string
generation_id: string | null
trace_id: string
+ // Session-target verdicts carry no $ai_trace_id, so the session id is the only thing that
+ // identifies what was graded. Absent on every other target.
+ session_id?: string | null
timestamp: string
evaluation_type?: EvaluationType
result_type?: EvaluationOutputType
@@ -129,6 +134,9 @@ export interface EvaluationRun {
sentiment_label?: string | null
sentiment_score?: number | null
applicable?: boolean
+ // A skipped run completed without grading anything. Its `result` is still false when the
+ // evaluation disallows N/A, so it has to be read alongside this rather than on its own.
+ skipped?: boolean
reasoning: string
status: 'completed' | 'failed' | 'running'
}
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index 04d42c0e93f5..7d758bed73d2 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -618,12 +618,14 @@ export interface EvaluationConditionApi {
/**
* * `generation` - Generation
* * `trace` - Trace
+ * * `session` - Session
*/
export type EvaluationTargetEnumApi = (typeof EvaluationTargetEnumApi)[keyof typeof EvaluationTargetEnumApi]
export const EvaluationTargetEnumApi = {
Generation: 'generation',
Trace: 'trace',
+ Session: 'session',
} as const
/**
@@ -699,32 +701,32 @@ export type EvaluationApiOutputConfig = {
}
/**
- * Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'.
+ * Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'.
*/
export type EvaluationApiTargetConfig =
| {
/** Wait a fixed window after the first matching generation, then evaluate. */
- strategy?: 'fixed_window'
+ strategy: 'fixed_window'
/**
- * Seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change runs already in flight.
+ * Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text.
* @minimum 10
- * @maximum 7200
+ * @maximum 604800
*/
window_seconds?: number
}
| {
- /** Evaluate once the trace has had no new activity for the quiet period. */
+ /** Evaluate once the unit has had no new activity for the quiet period. */
strategy: 'inactivity'
/**
- * Seconds without new trace activity before the trace counts as settled.
+ * Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text.
* @minimum 10
- * @maximum 1800
+ * @maximum 86400
*/
quiet_period_seconds?: number
/**
- * Hard cap in seconds on the total wait from the first matching generation, even if the trace stays active. Must be at least quiet_period_seconds.
+ * Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text.
* @minimum 60
- * @maximum 7200
+ * @maximum 604800
*/
max_age_seconds?: number
}
@@ -764,12 +766,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. When and how the trace run fires is controlled by target_config's settle strategy.
+ /** What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.
*
* * `generation` - Generation
- * * `trace` - Trace */
+ * * `trace` - Trace
+ * * `session` - Session */
target?: EvaluationTargetEnumApi
- /** Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'. */
+ /** Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'. */
target_config?: EvaluationApiTargetConfig
/** Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null. */
model_configuration?: ModelConfigurationApi | null
@@ -821,32 +824,32 @@ export type PatchedEvaluationApiOutputConfig = {
}
/**
- * Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'.
+ * Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'.
*/
export type PatchedEvaluationApiTargetConfig =
| {
/** Wait a fixed window after the first matching generation, then evaluate. */
- strategy?: 'fixed_window'
+ strategy: 'fixed_window'
/**
- * Seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change runs already in flight.
+ * Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text.
* @minimum 10
- * @maximum 7200
+ * @maximum 604800
*/
window_seconds?: number
}
| {
- /** Evaluate once the trace has had no new activity for the quiet period. */
+ /** Evaluate once the unit has had no new activity for the quiet period. */
strategy: 'inactivity'
/**
- * Seconds without new trace activity before the trace counts as settled.
+ * Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text.
* @minimum 10
- * @maximum 1800
+ * @maximum 86400
*/
quiet_period_seconds?: number
/**
- * Hard cap in seconds on the total wait from the first matching generation, even if the trace stays active. Must be at least quiet_period_seconds.
+ * Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text.
* @minimum 60
- * @maximum 7200
+ * @maximum 604800
*/
max_age_seconds?: number
}
@@ -886,12 +889,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. When and how the trace run fires is controlled by target_config's settle strategy.
+ /** What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.
*
* * `generation` - Generation
- * * `trace` - Trace */
+ * * `trace` - Trace
+ * * `session` - Session */
target?: EvaluationTargetEnumApi
- /** Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'. */
+ /** Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'. */
target_config?: PatchedEvaluationApiTargetConfig
/** Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null. */
model_configuration?: ModelConfigurationApi | null
@@ -911,6 +915,12 @@ export interface TestHogTargetConfigApi {
* @maximum 7200
*/
window_seconds?: number
+ /**
+ * For session samples: only sessions with no activity for this long are previewed, matching when a session evaluation would actually run.
+ * @minimum 10
+ * @maximum 86400
+ */
+ quiet_period_seconds?: number
}
export interface TestHogRequestApi {
@@ -929,25 +939,27 @@ export interface TestHogRequestApi {
allows_na?: boolean
/** Optional trigger conditions to filter which events are sampled. */
conditions?: TestHogRequestApiConditionsItem[]
- /** What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces and runs against trace-level globals — matching how the evaluation runs online.
+ /** What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces, and 'session' samples whole sessions that have gone quiet. Each target runs against the same globals it would run against online.
*
* * `generation` - Generation
- * * `trace` - Trace */
+ * * `trace` - Trace
+ * * `session` - Session */
target?: EvaluationTargetEnumApi
/** Target-specific preview settings. For a trace target, set window_seconds between 10 and 7200. */
target_config?: TestHogTargetConfigApi
}
export interface TestHogResultItemApi {
- /** Stable identifier for the sampled generation or trace. */
+ /** Stable identifier for the sampled generation, trace, or session. */
sample_id: string
- /** Type of sampled unit: generation or trace.
+ /** Type of sampled unit: generation, trace, or session.
*
* * `generation` - Generation
- * * `trace` - Trace */
+ * * `trace` - Trace
+ * * `session` - Session */
sample_type: EvaluationTargetEnumApi
/**
- * UUID of the sampled $ai_generation event, or null for a trace sample.
+ * UUID of the sampled $ai_generation event, or null for a trace or session sample.
* @nullable
*/
event_uuid: string | null
@@ -1453,6 +1465,8 @@ export interface EvaluationReportCitationApi {
generation_id?: string
/** Identifier of the trace cited by this report. */
trace_id?: string
+ /** Optional session identifier for session-target report citations. */
+ session_id?: string
/** Short explanation of why this example is cited. */
reason?: string
}
@@ -1534,7 +1548,8 @@ export interface EvaluationReportRunContentApi {
/** Evaluation target analyzed by this report run. Legacy runs without this field targeted generations.
*
* * `generation` - Generation
- * * `trace` - Trace */
+ * * `trace` - Trace
+ * * `session` - Session */
evaluation_target?: EvaluationTargetEnumApi
/** Agent-generated report headline. */
title?: string
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index ca25813cb96a..49e9fe807b19 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -207,18 +207,14 @@ export const evaluationsCreateBodyConditionsItemRolloutPercentageDefault = 100
export const evaluationsCreateBodyConditionsItemRolloutPercentageMin = 0
export const evaluationsCreateBodyConditionsItemRolloutPercentageMax = 100
-export const evaluationsCreateBodyTargetConfigOneStrategyDefault = `fixed_window`
-export const evaluationsCreateBodyTargetConfigOneWindowSecondsDefault = 1800
export const evaluationsCreateBodyTargetConfigOneWindowSecondsMin = 10
-export const evaluationsCreateBodyTargetConfigOneWindowSecondsMax = 7200
+export const evaluationsCreateBodyTargetConfigOneWindowSecondsMax = 604800
-export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsDefault = 300
export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMin = 10
-export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMax = 1800
+export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMax = 86400
-export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsDefault = 7200
export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMin = 60
-export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax = 7200
+export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax = 604800
export const evaluationsCreateBodyModelConfigurationOneModelMax = 100
@@ -305,51 +301,52 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({
'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')
+ .enum(['generation', 'trace', 'session'])
+ .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')
.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. When and how the trace run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace"
+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"
),
target_config: zod
.union([
zod.object({
strategy: zod
.enum(['fixed_window'])
- .default(evaluationsCreateBodyTargetConfigOneStrategyDefault)
.describe('Wait a fixed window after the first matching generation, then evaluate.'),
window_seconds: zod
.number()
.min(evaluationsCreateBodyTargetConfigOneWindowSecondsMin)
.max(evaluationsCreateBodyTargetConfigOneWindowSecondsMax)
- .default(evaluationsCreateBodyTargetConfigOneWindowSecondsDefault)
+ .optional()
.describe(
- 'Seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change runs already in flight.'
+ "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."
),
}),
zod.object({
strategy: zod
.enum(['inactivity'])
- .describe('Evaluate once the trace has had no new activity for the quiet period.'),
+ .describe('Evaluate once the unit has had no new activity for the quiet period.'),
quiet_period_seconds: zod
.number()
.min(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMin)
.max(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMax)
- .default(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsDefault)
- .describe('Seconds without new trace activity before the trace counts as settled.'),
+ .optional()
+ .describe(
+ "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."
+ ),
max_age_seconds: zod
.number()
.min(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMin)
.max(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax)
- .default(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsDefault)
+ .optional()
.describe(
- 'Hard cap in seconds on the total wait from the first matching generation, even if the trace stays active. Must be at least quiet_period_seconds.'
+ "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."
),
}),
])
.optional()
.describe(
- "Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'."
+ "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."
),
model_configuration: zod
.union([
@@ -399,18 +396,14 @@ export const evaluationsUpdateBodyConditionsItemRolloutPercentageDefault = 100
export const evaluationsUpdateBodyConditionsItemRolloutPercentageMin = 0
export const evaluationsUpdateBodyConditionsItemRolloutPercentageMax = 100
-export const evaluationsUpdateBodyTargetConfigOneStrategyDefault = `fixed_window`
-export const evaluationsUpdateBodyTargetConfigOneWindowSecondsDefault = 1800
export const evaluationsUpdateBodyTargetConfigOneWindowSecondsMin = 10
-export const evaluationsUpdateBodyTargetConfigOneWindowSecondsMax = 7200
+export const evaluationsUpdateBodyTargetConfigOneWindowSecondsMax = 604800
-export const evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsDefault = 300
export const evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsMin = 10
-export const evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsMax = 1800
+export const evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsMax = 86400
-export const evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsDefault = 7200
export const evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMin = 60
-export const evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMax = 7200
+export const evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMax = 604800
export const evaluationsUpdateBodyModelConfigurationOneModelMax = 100
@@ -497,51 +490,52 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod.object({
'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')
+ .enum(['generation', 'trace', 'session'])
+ .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')
.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. When and how the trace run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace"
+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"
),
target_config: zod
.union([
zod.object({
strategy: zod
.enum(['fixed_window'])
- .default(evaluationsUpdateBodyTargetConfigOneStrategyDefault)
.describe('Wait a fixed window after the first matching generation, then evaluate.'),
window_seconds: zod
.number()
.min(evaluationsUpdateBodyTargetConfigOneWindowSecondsMin)
.max(evaluationsUpdateBodyTargetConfigOneWindowSecondsMax)
- .default(evaluationsUpdateBodyTargetConfigOneWindowSecondsDefault)
+ .optional()
.describe(
- 'Seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change runs already in flight.'
+ "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."
),
}),
zod.object({
strategy: zod
.enum(['inactivity'])
- .describe('Evaluate once the trace has had no new activity for the quiet period.'),
+ .describe('Evaluate once the unit has had no new activity for the quiet period.'),
quiet_period_seconds: zod
.number()
.min(evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsMin)
.max(evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsMax)
- .default(evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsDefault)
- .describe('Seconds without new trace activity before the trace counts as settled.'),
+ .optional()
+ .describe(
+ "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."
+ ),
max_age_seconds: zod
.number()
.min(evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMin)
.max(evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMax)
- .default(evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsDefault)
+ .optional()
.describe(
- 'Hard cap in seconds on the total wait from the first matching generation, even if the trace stays active. Must be at least quiet_period_seconds.'
+ "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."
),
}),
])
.optional()
.describe(
- "Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'."
+ "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."
),
model_configuration: zod
.union([
@@ -591,18 +585,14 @@ export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMin = 0
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMax = 100
-export const evaluationsPartialUpdateBodyTargetConfigOneStrategyDefault = `fixed_window`
-export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsDefault = 1800
export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMin = 10
-export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMax = 7200
+export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMax = 604800
-export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsDefault = 300
export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMin = 10
-export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMax = 1800
+export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMax = 86400
-export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsDefault = 7200
export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMin = 60
-export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax = 7200
+export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax = 604800
export const evaluationsPartialUpdateBodyModelConfigurationOneModelMax = 100
@@ -691,51 +681,52 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({
'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')
+ .enum(['generation', 'trace', 'session'])
+ .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')
.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. When and how the trace run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace"
+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"
),
target_config: zod
.union([
zod.object({
strategy: zod
.enum(['fixed_window'])
- .default(evaluationsPartialUpdateBodyTargetConfigOneStrategyDefault)
.describe('Wait a fixed window after the first matching generation, then evaluate.'),
window_seconds: zod
.number()
.min(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMin)
.max(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMax)
- .default(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsDefault)
+ .optional()
.describe(
- 'Seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change runs already in flight.'
+ "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."
),
}),
zod.object({
strategy: zod
.enum(['inactivity'])
- .describe('Evaluate once the trace has had no new activity for the quiet period.'),
+ .describe('Evaluate once the unit has had no new activity for the quiet period.'),
quiet_period_seconds: zod
.number()
.min(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMin)
.max(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMax)
- .default(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsDefault)
- .describe('Seconds without new trace activity before the trace counts as settled.'),
+ .optional()
+ .describe(
+ "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."
+ ),
max_age_seconds: zod
.number()
.min(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMin)
.max(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax)
- .default(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsDefault)
+ .optional()
.describe(
- 'Hard cap in seconds on the total wait from the first matching generation, even if the trace stays active. Must be at least quiet_period_seconds.'
+ "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."
),
}),
])
.optional()
.describe(
- "Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'."
+ "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."
),
model_configuration: zod
.union([
@@ -788,6 +779,10 @@ export const evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsDefault = 1
export const evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMin = 10
export const evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMax = 7200
+export const evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsDefault = 3600
+export const evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMin = 10
+export const evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMax = 86400
+
export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({
source: zod
.string()
@@ -808,11 +803,11 @@ export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Optional trigger conditions to filter which events are sampled.'),
target: zod
- .enum(['generation', 'trace'])
- .describe('\* `generation` - Generation\n\* `trace` - Trace')
+ .enum(['generation', 'trace', 'session'])
+ .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')
.default(evaluationsTestHogCreateBodyTargetDefault)
.describe(
- "What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces and runs against trace-level globals — matching how the evaluation runs online.\n\n\* `generation` - Generation\n\* `trace` - Trace"
+ "What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces, and 'session' samples whole sessions that have gone quiet. Each target runs against the same globals it would run against online.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"
),
target_config: zod
.object({
@@ -822,6 +817,14 @@ export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({
.max(evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMax)
.default(evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsDefault)
.describe('Aggregation window for trace samples, in seconds.'),
+ quiet_period_seconds: zod
+ .number()
+ .min(evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMin)
+ .max(evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMax)
+ .default(evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsDefault)
+ .describe(
+ 'For session samples: only sessions with no activity for this long are previewed, matching when a session evaluation would actually run.'
+ ),
})
.optional()
.describe('Target-specific preview settings. For a trace target, set window_seconds between 10 and 7200.'),
diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.ts
index 6c83e25f65d9..02dd3c7882b4 100644
--- a/products/ai_observability/frontend/utils.test.ts
+++ b/products/ai_observability/frontend/utils.test.ts
@@ -36,6 +36,8 @@ interface EvaluationRunRowOverrides {
resultType?: EvaluationRunRow[10]
sentimentLabel?: EvaluationRunRow[11]
sentimentScore?: EvaluationRunRow[12]
+ sessionId?: EvaluationRunRow[13]
+ skipped?: EvaluationRunRow[14]
}
function makeEvaluationRunRow({
@@ -45,6 +47,8 @@ function makeEvaluationRunRow({
resultType = 'boolean',
sentimentLabel = null,
sentimentScore = null,
+ sessionId = null,
+ skipped = null,
}: EvaluationRunRowOverrides = {}): EvaluationRunRow {
return [
'run-1',
@@ -60,6 +64,8 @@ function makeEvaluationRunRow({
resultType,
sentimentLabel,
sentimentScore,
+ sessionId,
+ skipped,
]
}
@@ -104,6 +110,18 @@ describe('mapEvaluationRunRow', () => {
expect(run.result).toBeNull()
})
+ // A skip carries result: false when the evaluation disallows N/A, so anything reading the
+ // result alone reports a session that was never graded as one that failed.
+ it.each([
+ [true, true],
+ ['true', true],
+ [false, false],
+ [null, false],
+ ])('maps raw skipped %p to %p', (skipped, expected) => {
+ const run = mapEvaluationRunRow(makeEvaluationRunRow({ skipped }))
+ expect(run.skipped).toBe(expected)
+ })
+
it.each([true, 'true', 'True', '1'])('maps explicit pass result %p', (result) => {
expect(mapEvaluationRunRow(makeEvaluationRunRow({ result })).result).toBe(true)
})
diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.ts
index 1af7cf19c6cc..f36f39beb600 100644
--- a/products/ai_observability/frontend/utils.ts
+++ b/products/ai_observability/frontend/utils.ts
@@ -8,7 +8,11 @@ import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
import { hogql } from '~/queries/utils'
import type { SpanAggregation } from './aiObservabilityTraceDataLogic'
-import { EVALUATION_PASSED_HOGQL, EVALUATION_SUMMARY_MAX_RUNS } from './evaluations/constants'
+import {
+ EVALUATION_NOT_SKIPPED_HOGQL,
+ EVALUATION_PASSED_HOGQL,
+ EVALUATION_SUMMARY_MAX_RUNS,
+} from './evaluations/constants'
import type { EvaluationOutputType, EvaluationRun, EvaluationType } from './evaluations/types'
import {
AnthropicDocumentMessage,
@@ -1048,6 +1052,8 @@ type RawEvaluationRunRow = [
result_type: string | null,
sentiment_label: string | null,
sentiment_score: number | string | null,
+ session_id: string | null,
+ skipped: boolean | string | null,
]
export function normalizeEvaluationType(value: unknown): EvaluationType | undefined {
@@ -1149,7 +1155,9 @@ export function mapEvaluationRunRow(row: RawEvaluationRunRow): EvaluationRun {
evaluation_name: row[3] || 'Unknown Evaluation',
generation_id: row[4],
trace_id: row[5],
+ session_id: row[13] || null,
...normalizedResult,
+ skipped: isExplicitEvaluationPass(row[14]),
reasoning: row[7] || 'No reasoning provided',
status: 'completed' as const,
}
@@ -1158,17 +1166,24 @@ export function mapEvaluationRunRow(row: RawEvaluationRunRow): EvaluationRun {
export async function queryEvaluationRuns(params: {
evaluationId?: string
traceId?: string
+ sessionId?: string
+ /** Bounds the scan so it can prune partitions. Omitted for the trace and generation surfaces,
+ * which read a single unit's runs and have always been unbounded. */
+ lookbackDays?: number
forceRefresh?: boolean
}): Promise<EvaluationRun[]> {
- const { evaluationId, traceId, forceRefresh } = params
+ const { evaluationId, traceId, sessionId, lookbackDays, forceRefresh } = params
- const propertyValue = evaluationId || traceId
+ const propertyValue = evaluationId || traceId || sessionId
if (!propertyValue) {
- throw new Error('Either evaluationId or traceId must be provided')
+ throw new Error('One of evaluationId, traceId or sessionId must be provided')
}
- const propertyName = evaluationId ? '$ai_evaluation_id' : '$ai_trace_id'
+ // Session verdicts carry no $ai_trace_id, so they can only be found by $ai_session_id. Reading
+ // them through the same query as every other target keeps one row shape, one normalizer and
+ // one set of badge components across all three surfaces.
+ const propertyName = evaluationId ? '$ai_evaluation_id' : traceId ? '$ai_trace_id' : '$ai_session_id'
const query = hogql`
SELECT
@@ -1184,11 +1199,14 @@ export async function queryEvaluationRuns(params: {
properties.$ai_evaluation_runtime as evaluation_type,
properties.$ai_evaluation_result_type as result_type,
properties.$ai_sentiment_label as sentiment_label,
- properties.$ai_sentiment_score as sentiment_score
+ properties.$ai_sentiment_score as sentiment_score,
+ properties.$ai_session_id as session_id,
+ properties.$ai_evaluation_skipped as skipped
FROM events
WHERE
event = '$ai_evaluation'
AND ${hogql.raw(`properties.${propertyName}`)} = ${propertyValue}
+ ${lookbackDays ? hogql.raw(`AND timestamp >= now() - INTERVAL ${Math.floor(lookbackDays)} DAY`) : hogql.raw('')}
ORDER BY timestamp DESC
LIMIT ${EVALUATION_SUMMARY_MAX_RUNS}
`
@@ -1230,8 +1248,8 @@ export async function queryEvaluationRunsStats(params: {
const query = hogql`
SELECT
count() as total,
- countIf(properties.$ai_evaluation_result IS NOT NULL) as applicable,
- countIf(${hogql.raw(EVALUATION_PASSED_HOGQL)}) as passed
+ countIf(properties.$ai_evaluation_result IS NOT NULL AND ${hogql.raw(EVALUATION_NOT_SKIPPED_HOGQL)}) as applicable,
+ countIf(${hogql.raw(EVALUATION_PASSED_HOGQL)} AND ${hogql.raw(EVALUATION_NOT_SKIPPED_HOGQL)}) as passed
FROM events
WHERE
event = '$ai_evaluation'
diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yaml
index a0e21455b529..8a8dff58444d 100644
--- a/products/ai_observability/mcp/tools.yaml
+++ b/products/ai_observability/mcp/tools.yaml
@@ -353,8 +353,10 @@ tools:
Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and
model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a
boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional
- evaluation_config.source='user_messages'. Pass `enabled` as a boolean (true to start scoring new
- $ai_generation events immediately, false to create it paused). Results are '$ai_evaluation' events.
+ evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session' — a
+ session target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass
+ `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it
+ paused). Results are '$ai_evaluation' events.
llma-evaluation-delete:
operation: evaluations_destroy
enabled: true
@@ -576,9 +578,11 @@ tools:
description: >
Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the
evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and
- runs against trace-level globals. For trace previews, pass target_config.window_seconds to match the saved
- evaluation's aggregation window. Returns per-sample results (pass/fail/N/A), reasoning, and input/output
- previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.
+ runs against trace-level globals, 'session' samples whole sessions that have gone quiet and runs against
+ session-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's
+ aggregation window; for session previews, pass target_config.quiet_period_seconds to match its quiet period.
+ Returns per-sample results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog
+ code before creating or updating a 'hog' type evaluation.
llma-evaluation-update:
operation: evaluations_partial_update
enabled: true
@@ -596,7 +600,8 @@ tools:
and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or
provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to
hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain
- editable. provider_key_id may be null when no key is pinned.
+ editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or
+ 'session'.
llma-evaluation-update-full:
operation: evaluations_update
enabled: false
diff --git a/products/ai_observability/skills/creating-online-evaluations/SKILL.md b/products/ai_observability/skills/creating-online-evaluations/SKILL.md
index df6d33149989..764432361a38 100644
--- a/products/ai_observability/skills/creating-online-evaluations/SKILL.md
+++ b/products/ai_observability/skills/creating-online-evaluations/SKILL.md
@@ -76,6 +76,7 @@ Reach for `hog` first, escalate to `llm_judge` if there is no deterministic way
| ------------ | ------------------------------------------------------------------------------------------------------------------ |
| `generation` | Runs once for each matching `$ai_generation`, immediately after ingestion. This is the default. |
| `trace` | Runs once for the whole trace after the first matching generation and a configurable wait for the trace to finish. |
+| `session` | Runs once for the whole `$ai_session_id` session, after the session settles. |
For a trace target, send `"target": "trace"` plus a settle config that controls when the trace is
evaluated, discriminated on `strategy`:
@@ -88,23 +89,57 @@ evaluated, discriminated on `strategy`:
defaults to 5 minutes). `max_age_seconds` caps the total wait from the first matching generation
(1 minute to 2 hours, defaults to 2 hours, must be at least the quiet period).
+A `session` target takes the same settle config with session-sized bounds, and defaults to
+`inactivity` rather than `fixed_window`:
+
+- `{ "strategy": "inactivity", "quiet_period_seconds": 3600, "max_age_seconds": 86400 }` — evaluate
+ once the session has had no new activity for the quiet period (10 seconds to 24 hours, defaults
+ to 1 hour). `max_age_seconds` caps the total wait from the first matching generation (1 minute to
+ 7 days, defaults to 24 hours, must be at least the quiet period).
+- `{ "strategy": "fixed_window", "window_seconds": 1800 }` — evaluate a fixed wait after the first
+ matching generation (10 seconds to 7 days).
+
+A session evaluation only fires for events that carry `$ai_session_id`. Producers either set it on
+every generation or on none, so an SDK that does not set it will never trigger a session
+evaluation. `$ai_session_id` is not `$session_id`: the second is PostHog's product-analytics
+session and is unrelated.
+
+A session evaluation can also come back skipped rather than graded. The emitted `$ai_evaluation`
+event then carries `$ai_evaluation_skipped: true` and an `$ai_evaluation_skip_reason`, and its
+`$ai_evaluation_result` is `false` when the evaluation disallows N/A, so any analysis of pass rates
+has to exclude skipped runs rather than count them as failures. Sessions are skipped when
+they hold more than 2500 events (usually a session id shared across conversations), when nothing
+was found in the evaluation window, and, for an LLM judge, when the transcript is too long to send
+in full.
+
+A session is evaluated at most once per evaluation, for as long as the completed run stays inside
+Temporal's retention window. A session that resumes long after being evaluated may be evaluated
+again, so pick a quiet period long enough that the session is really finished. A longer quiet period
+costs only latency.
+
Conditions still match the generation that triggers the run; the evaluator itself receives
-the complete trace. Sentiment evaluations support only the generation target.
+the complete trace or session. Sentiment evaluations support only the generation target.
+
+New Hog source should use the globals shared by all targets:
-New Hog source should use the globals shared by both targets:
+| Global | Meaning |
+| -------------------------------------- | ---------------------------------------------------------------------------------------------------- |
+| `evaluation_events` | One generation event for a generation target, or every captured event for a trace or session target. |
+| `target` | The target's `type`, `id`, `total_cost_usd`, and `total_latency_seconds`. |
+| `item.input_text` / `item.output_text` | Best-effort readable projections; use these for length, keyword, and regex checks. |
+| `item.input` / `item.output` | Original serialized values; use these when the evaluator needs to parse the captured JSON itself. |
-| Global | Meaning |
-| -------------------------------------- | ------------------------------------------------------------------------------------------------- |
-| `evaluation_events` | One generation event for a generation target, or every captured event for a trace target. |
-| `target` | The target's `type`, `id`, `total_cost_usd`, and `total_latency_seconds`. |
-| `item.input_text` / `item.output_text` | Best-effort readable projections; use these for length, keyword, and regex checks. |
-| `item.input` / `item.output` | Original serialized values; use these when the evaluator needs to parse the captured JSON itself. |
+For a session target, `target.id` is the session id, and `target.total_cost_usd` /
+`target.total_latency_seconds` are summed across the session's traces. `total_latency_seconds` is time
+spent on AI work, not session wall-clock; the two can differ by orders of magnitude. Session wall-clock
+is derivable from `evaluation_events` timestamps.
Generation evaluations still expose top-level `input`, `output`, `properties`, and `event`. Trace evaluations
still expose their original `events` and `trace` globals. Those globals are kept for compatibility with saved
-evaluators. Do not use target-specific globals in new source that needs to work for both targets. The text
-projections recognize common provider payloads but are not authoritative; use `item.input` / `item.output` when
-exact structure matters.
+evaluators. Session evaluations do not carry them: session Hog source only receives `target` and
+`evaluation_events`. Do not use target-specific globals in new source that needs to work across targets. The
+text projections recognize common provider payloads but are not authoritative; use `item.input` / `item.output`
+when exact structure matters.
### 2.3 — Configure the LLM judge
diff --git a/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2 b/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2
index aae5ee9bf1b3..741a329522a0 100644
--- a/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2
+++ b/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2
@@ -14,8 +14,8 @@ schemas below are rendered from the backend Pydantic models at build time, so th
| `output_type` | yes | `"boolean"` for `hog`/`llm_judge`; `"sentiment"` for `sentiment`. |
| `output_config` | no | `{ "allows_na": bool }` for boolean; `{}` for sentiment. |
| `model_configuration` | llm_judge only | Provider + model; key ID optional. Rejected on `hog`/`sentiment`. |
-| `target` | no | `"generation"` (default) or `"trace"`. Sentiment supports only `"generation"`. |
-| `target_config` | trace only | Settle config discriminated on `strategy` (below); defaults to a 1800-second fixed window. |
+| `target` | no | `"generation"` (default), `"trace"`, or `"session"`. Sentiment supports only `"generation"`. |
+| `target_config` | trace/session only | Settle config discriminated on `strategy` (below); defaults to a 30-minute fixed window for `trace`, and to a 1-hour inactivity window for `session`. |
| `conditions` | no | Trigger condition sets (below). For traces, conditions match the triggering generation. |
| `enabled` | no | Defaults to `false`. Create disabled, then flip with `llma-evaluation-update`. |
@@ -31,9 +31,24 @@ Valid `(evaluation_type, output_type)` pairs: `(hog, boolean)`, `(llm_judge, boo
- `{ "strategy": "inactivity", "quiet_period_seconds": 10..1800, "max_age_seconds": 60..7200 }`
evaluates once no new activity arrived for the quiet period (defaults to 300), capped at
`max_age_seconds` (defaults to 7200, must be at least the quiet period) from the first one.
-- Conditions always match generation properties. For a trace target, that matching generation schedules the
- eventual whole-trace evaluation.
-- Sentiment evaluations cannot use the trace target.
+- `"target": "session"` runs once for the whole `$ai_session_id` session, after the session settles.
+ `target_config` picks the settle strategy with session-sized bounds:
+ - `{ "strategy": "inactivity", "quiet_period_seconds": 10..86400, "max_age_seconds": 60..604800 }`
+ evaluates once no new session activity arrived for the quiet period (defaults to 3600), capped at
+ `max_age_seconds` (defaults to 86400, must be at least the quiet period) from the first one. This
+ is the default strategy for a session target.
+ - `{ "strategy": "fixed_window", "window_seconds": 10..604800 }` waits a fixed delay after the first
+ matching generation (defaults to 1800).
+ - A session evaluation only fires for events that carry `$ai_session_id`. Producers set it on every
+ generation or on none, so an SDK that never sets it will never trigger a session evaluation.
+ `$ai_session_id` is not `$session_id`, PostHog's product-analytics session; the two are unrelated.
+ - A session is evaluated at most once per evaluation, for as long as the completed run stays inside
+ Temporal's retention window. A session that resumes long after being evaluated may be evaluated
+ again.
+
+- Conditions always match generation properties. For a trace or session target, that matching
+ generation schedules the eventual whole-unit evaluation.
+- Sentiment evaluations cannot use the trace or session target.
## `evaluation_config` by type
@@ -149,11 +164,21 @@ Or evaluate when the trace goes quiet instead of after a fixed delay:
}
```
+The same Hog source also works for a whole session, once no new activity has arrived for the quiet period:
+
+```json
+{
+ "target": "session",
+ "target_config": { "strategy": "inactivity", "quiet_period_seconds": 3600, "max_age_seconds": 86400 }
+}
+```
+
New Hog source should use the shared `evaluation_events` and `target` globals. Top-level generation globals
such as `input`, `output`, `properties`, and `event`, plus the trace-only `events` and `trace` globals, remain
-available for compatibility with saved evaluators. `item.input_text` and `item.output_text` are best-effort
-readable projections of common provider payloads; use raw `item.input` and `item.output` when exact structure
-matters.
+available for compatibility with saved evaluators. Session evaluations do not carry the legacy `events` /
+`trace` globals: session Hog source only receives `evaluation_events` and `target`. `item.input_text` and
+`item.output_text` are best-effort readable projections of common provider payloads; use raw `item.input`
+and `item.output` when exact structure matters.
### LLM judge
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index e5e322350249..75a71b25adf7 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -5260,7 +5260,7 @@
}
},
"llma-evaluation-create": {
- "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. Pass `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it paused). Results are '$ai_evaluation' events.",
+ "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session' — a session target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it paused). Results are '$ai_evaluation' events.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Create evaluation",
@@ -5443,7 +5443,7 @@
"requires_ai_consent": true
},
"llma-evaluation-test-hog": {
- "description": "Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and runs against trace-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's aggregation window. Returns per-sample results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.",
+ "description": "Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and runs against trace-level globals, 'session' samples whole sessions that have gone quiet and runs against session-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's aggregation window; for session previews, pass target_config.quiet_period_seconds to match its quiet period. Returns per-sample results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Test Hog evaluation code",
@@ -5457,7 +5457,7 @@
}
},
"llma-evaluation-update": {
- "description": "Partially update an AI observability evaluation. Requires the evaluation `id` (UUID) — if you don't have it, call llma-evaluation-list first to look it up by name. Toggle enabled, change its type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned.",
+ "description": "Partially update an AI observability evaluation. Requires the evaluation `id` (UUID) — if you don't have it, call llma-evaluation-list first to look it up by name. Toggle enabled, change its type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or 'session'.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Update evaluation",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 2ae995571a7f..df649341b5f3 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5555,7 +5555,7 @@
}
},
"llma-evaluation-create": {
- "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. Pass `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it paused). Results are '$ai_evaluation' events.",
+ "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session' — a session target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it paused). Results are '$ai_evaluation' events.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Create evaluation",
@@ -5738,7 +5738,7 @@
"requires_ai_consent": true
},
"llma-evaluation-test-hog": {
- "description": "Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and runs against trace-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's aggregation window. Returns per-sample results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.",
+ "description": "Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and runs against trace-level globals, 'session' samples whole sessions that have gone quiet and runs against session-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's aggregation window; for session previews, pass target_config.quiet_period_seconds to match its quiet period. Returns per-sample results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Test Hog evaluation code",
@@ -5752,7 +5752,7 @@
}
},
"llma-evaluation-update": {
- "description": "Partially update an AI observability evaluation. Requires the evaluation `id` (UUID) — if you don't have it, call llma-evaluation-list first to look it up by name. Toggle enabled, change its type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned.",
+ "description": "Partially update an AI observability evaluation. Requires the evaluation `id` (UUID) — if you don't have it, call llma-evaluation-list first to look it up by name. Toggle enabled, change its type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or 'session'.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Update evaluation",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 17d7e5802b27..e4bafbf2b57e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -27069,30 +27069,30 @@ export namespace Schemas {
};
/**
- * Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'.
+ * Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'.
*/
export type EvaluationTargetConfig = {
/** Wait a fixed window after the first matching generation, then evaluate. */
- strategy?: 'fixed_window';
+ strategy: 'fixed_window';
/**
- * Seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change runs already in flight.
+ * Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text.
* @minimum 10
- * @maximum 7200
+ * @maximum 604800
*/
window_seconds?: number;
} | {
- /** Evaluate once the trace has had no new activity for the quiet period. */
+ /** Evaluate once the unit has had no new activity for the quiet period. */
strategy: 'inactivity';
/**
- * Seconds without new trace activity before the trace counts as settled.
+ * Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text.
* @minimum 10
- * @maximum 1800
+ * @maximum 86400
*/
quiet_period_seconds?: number;
/**
- * Hard cap in seconds on the total wait from the first matching generation, even if the trace stays active. Must be at least quiet_period_seconds.
+ * Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text.
* @minimum 60
- * @maximum 7200
+ * @maximum 604800
*/
max_age_seconds?: number;
};
@@ -27187,6 +27187,7 @@ export namespace Schemas {
/**
* * `generation` - Generation
* * `trace` - Trace
+ * * `session` - Session
*/
export type EvaluationTargetEnum = typeof EvaluationTargetEnum[keyof typeof EvaluationTargetEnum];
@@ -27194,6 +27195,7 @@ export namespace Schemas {
export const EvaluationTargetEnum = {
Generation: 'generation',
Trace: 'trace',
+ Session: 'session',
} as const;
/**
@@ -27273,12 +27275,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. When and how the trace run fires is controlled by target_config's settle strategy.
+ /** What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.
*
* * `generation` - Generation
- * * `trace` - Trace */
+ * * `trace` - Trace
+ * * `session` - Session */
target?: EvaluationTargetEnum;
- /** Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'. */
+ /** Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'. */
target_config?: EvaluationTargetConfig;
/** Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null. */
model_configuration?: ModelConfiguration | null;
@@ -27454,6 +27457,8 @@ export namespace Schemas {
generation_id?: string;
/** Identifier of the trace cited by this report. */
trace_id?: string;
+ /** Optional session identifier for session-target report citations. */
+ session_id?: string;
/** Short explanation of why this example is cited. */
reason?: string;
}
@@ -27543,7 +27548,8 @@ export namespace Schemas {
/** Evaluation target analyzed by this report run. Legacy runs without this field targeted generations.
*
* * `generation` - Generation
- * * `trace` - Trace */
+ * * `trace` - Trace
+ * * `session` - Session */
evaluation_target?: EvaluationTargetEnum;
/** Agent-generated report headline. */
title?: string;
@@ -52286,30 +52292,30 @@ export namespace Schemas {
};
/**
- * Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'.
+ * Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'.
*/
export type PatchedEvaluationTargetConfig = {
/** Wait a fixed window after the first matching generation, then evaluate. */
- strategy?: 'fixed_window';
+ strategy: 'fixed_window';
/**
- * Seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change runs already in flight.
+ * Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text.
* @minimum 10
- * @maximum 7200
+ * @maximum 604800
*/
window_seconds?: number;
} | {
- /** Evaluate once the trace has had no new activity for the quiet period. */
+ /** Evaluate once the unit has had no new activity for the quiet period. */
strategy: 'inactivity';
/**
- * Seconds without new trace activity before the trace counts as settled.
+ * Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text.
* @minimum 10
- * @maximum 1800
+ * @maximum 86400
*/
quiet_period_seconds?: number;
/**
- * Hard cap in seconds on the total wait from the first matching generation, even if the trace stays active. Must be at least quiet_period_seconds.
+ * Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text.
* @minimum 60
- * @maximum 7200
+ * @maximum 604800
*/
max_age_seconds?: number;
};
@@ -52349,12 +52355,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. When and how the trace run fires is controlled by target_config's settle strategy.
+ /** What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.
*
* * `generation` - Generation
- * * `trace` - Trace */
+ * * `trace` - Trace
+ * * `session` - Session */
target?: EvaluationTargetEnum;
- /** Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'. */
+ /** Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'. */
target_config?: PatchedEvaluationTargetConfig;
/** Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null. */
model_configuration?: ModelConfiguration | null;
@@ -73851,6 +73858,12 @@ export namespace Schemas {
* @maximum 7200
*/
window_seconds?: number;
+ /**
+ * For session samples: only sessions with no activity for this long are previewed, matching when a session evaluation would actually run.
+ * @minimum 10
+ * @maximum 86400
+ */
+ quiet_period_seconds?: number;
}
export interface TestHogRequest {
@@ -73869,25 +73882,27 @@ export namespace Schemas {
allows_na?: boolean;
/** Optional trigger conditions to filter which events are sampled. */
conditions?: TestHogRequestConditionsItem[];
- /** What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces and runs against trace-level globals — matching how the evaluation runs online.
+ /** What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces, and 'session' samples whole sessions that have gone quiet. Each target runs against the same globals it would run against online.
*
* * `generation` - Generation
- * * `trace` - Trace */
+ * * `trace` - Trace
+ * * `session` - Session */
target?: EvaluationTargetEnum;
/** Target-specific preview settings. For a trace target, set window_seconds between 10 and 7200. */
target_config?: TestHogTargetConfig;
}
export interface TestHogResultItem {
- /** Stable identifier for the sampled generation or trace. */
+ /** Stable identifier for the sampled generation, trace, or session. */
sample_id: string;
- /** Type of sampled unit: generation or trace.
+ /** Type of sampled unit: generation, trace, or session.
*
* * `generation` - Generation
- * * `trace` - Trace */
+ * * `trace` - Trace
+ * * `session` - Session */
sample_type: EvaluationTargetEnum;
/**
- * UUID of the sampled $ai_generation event, or null for a trace sample.
+ * UUID of the sampled $ai_generation event, or null for a trace or session sample.
* @nullable
*/
event_uuid: string | null;
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index 3e3abb85c796..9b055272e7ed 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -379,18 +379,14 @@ export const evaluationsCreateBodyConditionsItemRolloutPercentageDefault = 100
export const evaluationsCreateBodyConditionsItemRolloutPercentageMin = 0
export const evaluationsCreateBodyConditionsItemRolloutPercentageMax = 100
-export const evaluationsCreateBodyTargetConfigOneStrategyDefault = `fixed_window`
-export const evaluationsCreateBodyTargetConfigOneWindowSecondsDefault = 1800
export const evaluationsCreateBodyTargetConfigOneWindowSecondsMin = 10
-export const evaluationsCreateBodyTargetConfigOneWindowSecondsMax = 7200
+export const evaluationsCreateBodyTargetConfigOneWindowSecondsMax = 604800
-export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsDefault = 300
export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMin = 10
-export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMax = 1800
+export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMax = 86400
-export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsDefault = 7200
export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMin = 60
-export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax = 7200
+export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax = 604800
export const evaluationsCreateBodyModelConfigurationOneModelMax = 100
@@ -477,51 +473,52 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({
'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')
+ .enum(['generation', 'trace', 'session'])
+ .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')
.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. When and how the trace run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace"
+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"
),
target_config: zod
.union([
zod.object({
strategy: zod
.enum(['fixed_window'])
- .default(evaluationsCreateBodyTargetConfigOneStrategyDefault)
.describe('Wait a fixed window after the first matching generation, then evaluate.'),
window_seconds: zod
.number()
.min(evaluationsCreateBodyTargetConfigOneWindowSecondsMin)
.max(evaluationsCreateBodyTargetConfigOneWindowSecondsMax)
- .default(evaluationsCreateBodyTargetConfigOneWindowSecondsDefault)
+ .optional()
.describe(
- 'Seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change runs already in flight.'
+ "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."
),
}),
zod.object({
strategy: zod
.enum(['inactivity'])
- .describe('Evaluate once the trace has had no new activity for the quiet period.'),
+ .describe('Evaluate once the unit has had no new activity for the quiet period.'),
quiet_period_seconds: zod
.number()
.min(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMin)
.max(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMax)
- .default(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsDefault)
- .describe('Seconds without new trace activity before the trace counts as settled.'),
+ .optional()
+ .describe(
+ "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."
+ ),
max_age_seconds: zod
.number()
.min(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMin)
.max(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax)
- .default(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsDefault)
+ .optional()
.describe(
- 'Hard cap in seconds on the total wait from the first matching generation, even if the trace stays active. Must be at least quiet_period_seconds.'
+ "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."
),
}),
])
.optional()
.describe(
- "Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'."
+ "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."
),
model_configuration: zod
.union([
@@ -589,18 +586,14 @@ export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMin = 0
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMax = 100
-export const evaluationsPartialUpdateBodyTargetConfigOneStrategyDefault = `fixed_window`
-export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsDefault = 1800
export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMin = 10
-export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMax = 7200
+export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMax = 604800
-export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsDefault = 300
export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMin = 10
-export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMax = 1800
+export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMax = 86400
-export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsDefault = 7200
export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMin = 60
-export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax = 7200
+export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax = 604800
export const evaluationsPartialUpdateBodyModelConfigurationOneModelMax = 100
@@ -689,51 +682,52 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({
'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')
+ .enum(['generation', 'trace', 'session'])
+ .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')
.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. When and how the trace run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace"
+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"
),
target_config: zod
.union([
zod.object({
strategy: zod
.enum(['fixed_window'])
- .default(evaluationsPartialUpdateBodyTargetConfigOneStrategyDefault)
.describe('Wait a fixed window after the first matching generation, then evaluate.'),
window_seconds: zod
.number()
.min(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMin)
.max(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMax)
- .default(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsDefault)
+ .optional()
.describe(
- 'Seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change runs already in flight.'
+ "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."
),
}),
zod.object({
strategy: zod
.enum(['inactivity'])
- .describe('Evaluate once the trace has had no new activity for the quiet period.'),
+ .describe('Evaluate once the unit has had no new activity for the quiet period.'),
quiet_period_seconds: zod
.number()
.min(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMin)
.max(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMax)
- .default(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsDefault)
- .describe('Seconds without new trace activity before the trace counts as settled.'),
+ .optional()
+ .describe(
+ "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."
+ ),
max_age_seconds: zod
.number()
.min(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMin)
.max(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax)
- .default(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsDefault)
+ .optional()
.describe(
- 'Hard cap in seconds on the total wait from the first matching generation, even if the trace stays active. Must be at least quiet_period_seconds.'
+ "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."
),
}),
])
.optional()
.describe(
- "Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'."
+ "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."
),
model_configuration: zod
.union([
@@ -805,6 +799,10 @@ export const evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsDefault = 1
export const evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMin = 10
export const evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMax = 7200
+export const evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsDefault = 3600
+export const evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMin = 10
+export const evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMax = 86400
+
export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({
source: zod
.string()
@@ -825,11 +823,11 @@ export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Optional trigger conditions to filter which events are sampled.'),
target: zod
- .enum(['generation', 'trace'])
- .describe('\* `generation` - Generation\n\* `trace` - Trace')
+ .enum(['generation', 'trace', 'session'])
+ .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')
.default(evaluationsTestHogCreateBodyTargetDefault)
.describe(
- "What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces and runs against trace-level globals — matching how the evaluation runs online.\n\n\* `generation` - Generation\n\* `trace` - Trace"
+ "What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces, and 'session' samples whole sessions that have gone quiet. Each target runs against the same globals it would run against online.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"
),
target_config: zod
.object({
@@ -839,6 +837,14 @@ export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({
.max(evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMax)
.default(evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsDefault)
.describe('Aggregation window for trace samples, in seconds.'),
+ quiet_period_seconds: zod
+ .number()
+ .min(evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMin)
+ .max(evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMax)
+ .default(evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsDefault)
+ .describe(
+ 'For session samples: only sessions with no activity for this long are previewed, matching when a session evaluation would actually run.'
+ ),
})
.optional()
.describe('Target-specific preview settings. For a trace target, set window_seconds between 10 and 7200.'),
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.json
index f5a14793a679..5c59fa07d977 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
@@ -167,8 +167,8 @@
"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. When and how the trace run fires is controlled by target_config's settle strategy.\n\n* `generation` - Generation\n* `trace` - Trace",
- "enum": ["generation", "trace"],
+ "description": "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n* `generation` - Generation\n* `trace` - Trace\n* `session` - Session",
+ "enum": ["generation", "trace", "session"],
"type": "string"
},
"target_config": {
@@ -176,39 +176,36 @@
{
"properties": {
"strategy": {
- "default": "fixed_window",
"description": "Wait a fixed window after the first matching generation, then evaluate.",
"enum": ["fixed_window"],
"type": "string"
},
"window_seconds": {
- "default": 1800,
- "description": "Seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change runs already in flight.",
- "maximum": 7200,
+ "description": "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text.",
+ "maximum": 604800,
"minimum": 10,
"type": "number"
}
},
+ "required": ["strategy"],
"type": "object"
},
{
"properties": {
"max_age_seconds": {
- "default": 7200,
- "description": "Hard cap in seconds on the total wait from the first matching generation, even if the trace stays active. Must be at least quiet_period_seconds.",
- "maximum": 7200,
+ "description": "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text.",
+ "maximum": 604800,
"minimum": 60,
"type": "number"
},
"quiet_period_seconds": {
- "default": 300,
- "description": "Seconds without new trace activity before the trace counts as settled.",
- "maximum": 1800,
+ "description": "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text.",
+ "maximum": 86400,
"minimum": 10,
"type": "number"
},
"strategy": {
- "description": "Evaluate once the trace has had no new activity for the quiet period.",
+ "description": "Evaluate once the unit has had no new activity for the quiet period.",
"enum": ["inactivity"],
"type": "string"
}
@@ -217,7 +214,7 @@
"type": "object"
}
],
- "description": "Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'."
+ "description": "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."
}
},
"required": ["name", "evaluation_type", "output_type"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json
index ed53768a1eb1..9f9acc0f3ab9 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json
@@ -31,13 +31,20 @@
},
"target": {
"default": "generation",
- "description": "What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces and runs against trace-level globals — matching how the evaluation runs online.\n\n* `generation` - Generation\n* `trace` - Trace",
- "enum": ["generation", "trace"],
+ "description": "What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces, and 'session' samples whole sessions that have gone quiet. Each target runs against the same globals it would run against online.\n\n* `generation` - Generation\n* `trace` - Trace\n* `session` - Session",
+ "enum": ["generation", "trace", "session"],
"type": "string"
},
"target_config": {
"description": "Target-specific preview settings. For a trace target, set window_seconds between 10 and 7200.",
"properties": {
+ "quiet_period_seconds": {
+ "default": 3600,
+ "description": "For session samples: only sessions with no activity for this long are previewed, matching when a session evaluation would actually run.",
+ "maximum": 86400,
+ "minimum": 10,
+ "type": "number"
+ },
"window_seconds": {
"default": 1800,
"description": "Aggregation window for trace samples, in seconds.",
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.json
index a6343ffdad93..5be10dd479c0 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
@@ -171,8 +171,8 @@
"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. When and how the trace run fires is controlled by target_config's settle strategy.\n\n* `generation` - Generation\n* `trace` - Trace",
- "enum": ["generation", "trace"],
+ "description": "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n* `generation` - Generation\n* `trace` - Trace\n* `session` - Session",
+ "enum": ["generation", "trace", "session"],
"type": "string"
},
"target_config": {
@@ -180,39 +180,36 @@
{
"properties": {
"strategy": {
- "default": "fixed_window",
"description": "Wait a fixed window after the first matching generation, then evaluate.",
"enum": ["fixed_window"],
"type": "string"
},
"window_seconds": {
- "default": 1800,
- "description": "Seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change runs already in flight.",
- "maximum": 7200,
+ "description": "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text.",
+ "maximum": 604800,
"minimum": 10,
"type": "number"
}
},
+ "required": ["strategy"],
"type": "object"
},
{
"properties": {
"max_age_seconds": {
- "default": 7200,
- "description": "Hard cap in seconds on the total wait from the first matching generation, even if the trace stays active. Must be at least quiet_period_seconds.",
- "maximum": 7200,
+ "description": "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text.",
+ "maximum": 604800,
"minimum": 60,
"type": "number"
},
"quiet_period_seconds": {
- "default": 300,
- "description": "Seconds without new trace activity before the trace counts as settled.",
- "maximum": 1800,
+ "description": "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text.",
+ "maximum": 86400,
"minimum": 10,
"type": "number"
},
"strategy": {
- "description": "Evaluate once the trace has had no new activity for the quiet period.",
+ "description": "Evaluate once the unit has had no new activity for the quiet period.",
"enum": ["inactivity"],
"type": "string"
}
@@ -221,7 +218,7 @@
"type": "object"
}
],
- "description": "Target-specific config. For 'trace' target: a settle config discriminated on `strategy` — 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Missing strategy means fixed_window. Empty for 'generation'."
+ "description": "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."
}
},
"required": ["id"],