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): add settling strategies for trace evaluations (#72956)

Carlos Marchala35387ac436b
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index c6afacd68e3d..f9c13cd17a8b 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -346,6 +346,7 @@ export const FEATURE_FLAGS = {
LIVE_EVENTS_RICH_FILTERS: 'live-events-rich-filters', // owner: @jordanm-posthog #team-web-analytics
LLM_ANALYTICS_CLUSTERING_ADMIN: 'llm-analytics-clustering-admin', // owner: #team-ai-observability
LLM_ANALYTICS_DATASETS: 'llm-analytics-datasets', // owner: #team-ai-observability #team-posthog-ai
+ LLM_ANALYTICS_EVAL_SETTLING_STRATEGY: 'llm-analytics-eval-settling-strategy', // owner: #team-ai-observability
LLM_ANALYTICS_EVALUATIONS_START_WITH_AI: 'llm-analytics-evaluations-start-with-ai', // owner: #team-ai-observability
LLM_ANALYTICS_OFFLINE_EVALS: 'llm-analytics-offline-evals', // owner: #team-ai-observability
LLM_ANALYTICS_TAGS: 'llm-analytics-tags', // owner: #team-ai-observability
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 101da7235e62..082affba531e 100644
--- a/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.test.ts
+++ b/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.test.ts
@@ -522,51 +522,81 @@ describe('Evaluation Scheduler', () => {
} as unknown as import('~/ai-observability/services/tagger-manager.service').TaggerManagerService
temporalService = {
startEvaluationRunWorkflow: jest.fn().mockResolvedValue(undefined),
- startTraceEvaluationRunWorkflow: jest.fn().mockResolvedValue(undefined),
+ startAggregateEvaluationWorkflow: jest.fn().mockResolvedValue(undefined),
startTaggerRunWorkflow: jest.fn().mockResolvedValue(undefined),
} as unknown as import('~/ai-observability/services/temporal.service').TemporalService
})
- it('dispatches the trace workflow with trace context and the config window', async () => {
+ it('starts the aggregate workflow with trace context and the resolved fixed-window settle config', async () => {
const event = createAiGenerationEvent(teamId, {
- properties: JSON.stringify({ $ai_trace_id: 'trace-1', $session_id: 'session-1' }),
+ properties: JSON.stringify({ $ai_trace_id: 'trace-abc', $session_id: null }),
})
const evaluation = createEvaluation({
+ id: 'eval-1',
team_id: teamId,
target: 'trace',
- target_config: { window_seconds: 90 },
+ target_config: { window_seconds: 900 },
conditions: [createEvaluationCondition({ bytecode: ['_H', 1, 32, true], rollout_percentage: 100 })],
})
;(evaluationManager.getEvaluationsForTeams as jest.Mock).mockResolvedValue({ [teamId]: [evaluation] })
await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService)
- expect(temporalService.startTraceEvaluationRunWorkflow).toHaveBeenCalledWith(
- evaluation.id,
- event,
- 'trace-1',
- 'session-1',
- 90
+ expect(temporalService.startAggregateEvaluationWorkflow).toHaveBeenCalledWith(
+ 'eval-1',
+ expect.objectContaining({ uuid: event.uuid }),
+ 'trace-abc',
+ null,
+ { strategy: 'fixed_window', window_seconds: 900 }
)
expect(temporalService.startEvaluationRunWorkflow).not.toHaveBeenCalled()
})
it('falls back to the default window when target_config has none', async () => {
const event = createAiGenerationEvent(teamId, {
- properties: JSON.stringify({ $ai_trace_id: 'trace-1' }),
+ properties: JSON.stringify({ $ai_trace_id: 'trace-abc', $session_id: null }),
})
const evaluation = createEvaluation({
+ id: 'eval-1',
team_id: teamId,
target: 'trace',
- target_config: {},
conditions: [createEvaluationCondition({ bytecode: ['_H', 1, 32, true], rollout_percentage: 100 })],
})
;(evaluationManager.getEvaluationsForTeams as jest.Mock).mockResolvedValue({ [teamId]: [evaluation] })
await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService)
- const call = (temporalService.startTraceEvaluationRunWorkflow as jest.Mock).mock.calls[0]
- expect(call[4]).toBe(30 * 60)
+ expect(temporalService.startAggregateEvaluationWorkflow).toHaveBeenCalledWith(
+ 'eval-1',
+ expect.objectContaining({ uuid: event.uuid }),
+ 'trace-abc',
+ null,
+ { strategy: 'fixed_window', window_seconds: 1800 }
+ )
+ expect(temporalService.startEvaluationRunWorkflow).not.toHaveBeenCalled()
+ })
+
+ it('passes the resolved inactivity settle config for inactivity evals', async () => {
+ const event = createAiGenerationEvent(teamId, {
+ properties: JSON.stringify({ $ai_trace_id: 'trace-xyz' }),
+ })
+ const evaluation = createEvaluation({
+ team_id: teamId,
+ target: 'trace',
+ target_config: { strategy: 'inactivity', quiet_period_seconds: 120 },
+ 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(
+ evaluation.id,
+ expect.anything(),
+ expect.any(String),
+ null,
+ { strategy: 'inactivity', quiet_period_seconds: 120, max_age_seconds: 7200 }
+ )
})
it('skips trace-target evaluations when the event carries no trace id', async () => {
@@ -582,7 +612,7 @@ describe('Evaluation Scheduler', () => {
await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService)
- expect(temporalService.startTraceEvaluationRunWorkflow).not.toHaveBeenCalled()
+ expect(temporalService.startAggregateEvaluationWorkflow).not.toHaveBeenCalled()
expect(temporalService.startEvaluationRunWorkflow).not.toHaveBeenCalled()
})
@@ -604,7 +634,7 @@ describe('Evaluation Scheduler', () => {
event,
evaluation.evaluation_type
)
- expect(temporalService.startTraceEvaluationRunWorkflow).not.toHaveBeenCalled()
+ expect(temporalService.startAggregateEvaluationWorkflow).not.toHaveBeenCalled()
})
})
diff --git a/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.ts b/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.ts
index 48223f13654f..c77a177892a0 100644
--- a/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.ts
+++ b/nodejs/src/ai-observability/evaluation-scheduler/evaluation-scheduler.ts
@@ -18,10 +18,10 @@ import { EvaluationManagerService } from '~/ai-observability/services/evaluation
import { ProviderKeyManagerService } from '~/ai-observability/services/provider-key-manager.service'
import { TaggerManagerService } from '~/ai-observability/services/tagger-manager.service'
import {
- DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS,
TemporalService,
TemporalServiceConfig,
isEvaluationWorkflowRuntime,
+ resolveSettleConfig,
} from '~/ai-observability/services/temporal.service'
import { Evaluation, EvaluationConditionSet, Matchable, Tagger } from '~/ai-observability/types'
import { execHog } from '~/cdp/utils/hog-exec'
@@ -476,16 +476,15 @@ async function processEventEvaluationMatch(
evaluationMatchesCounter.labels({ outcome: 'matched', type: 'evaluation' }).inc()
if (isTraceTarget && traceContext?.traceId) {
- // No isEvaluationWorkflowRuntime guard here: the trace workflow validates evaluation_type
+ // No isEvaluationWorkflowRuntime guard here: the aggregate workflow validates evaluation_type
// server-side and rejects unsupported types as a non-retryable ApplicationError.
- const windowSeconds =
- evaluationDefinition.target_config?.window_seconds ?? DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS
- await temporalService.startTraceEvaluationRunWorkflow(
+ const settle = resolveSettleConfig(evaluationDefinition.target_config)
+ await temporalService.startAggregateEvaluationWorkflow(
evaluationDefinition.id,
event,
traceContext.traceId,
traceContext.sessionId,
- windowSeconds
+ settle
)
} else {
const evaluationRuntime = evaluationDefinition.evaluation_type
diff --git a/nodejs/src/ai-observability/services/temporal.service.test.ts b/nodejs/src/ai-observability/services/temporal.service.test.ts
index 830750e10b3a..1675e3d5472b 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 { DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS, TemporalService, workflowSafeTraceId } from './temporal.service'
+import { TemporalService, resolveSettleConfig, workflowSafeTraceId } from './temporal.service'
import type { EvaluationWorkflowRuntime, TemporalServiceConfig } from './temporal.service'
jest.mock('@temporalio/client')
@@ -276,45 +276,65 @@ describe('TemporalService', () => {
})
})
- describe('trace evaluation workflows', () => {
- it('starts the trace workflow with slim inputs and the passed aggregation window', async () => {
+ describe('aggregate evaluation workflows', () => {
+ it('starts the aggregate workflow with the resolved settle config', async () => {
const mockEvent = createMockEvent()
- await service.startTraceEvaluationRunWorkflow('eval-123', mockEvent, 'trace-789', 'session-1', 60)
+ await service.startAggregateEvaluationWorkflow('eval-123', mockEvent, 'trace-abc', 'session-1', {
+ strategy: 'inactivity',
+ quiet_period_seconds: 120,
+ max_age_seconds: 600,
+ })
- expect(mockClient.workflow.start).toHaveBeenCalledWith('run-trace-evaluation', {
- taskQueue: 'llm-analytics-evals-task-queue',
- workflowId: 'llma-trace-eval-eval-123-trace-789',
- workflowIdConflictPolicy: 'USE_EXISTING',
- workflowIdReusePolicy: 'ALLOW_DUPLICATE_FAILED_ONLY',
- workflowTaskTimeout: '2 minutes',
+ expect(mockClient.workflow.start).toHaveBeenCalledWith('run-aggregate-evaluation', {
args: [
{
evaluation_id: 'eval-123',
- team_id: 1,
- trace_id: 'trace-789',
- distinct_id: 'test-user',
+ team_id: mockEvent.team_id,
+ trace_id: 'trace-abc',
+ distinct_id: mockEvent.distinct_id,
session_id: 'session-1',
- window_seconds: 60,
+ settle: { strategy: 'inactivity', quiet_period_seconds: 120, max_age_seconds: 600 },
},
],
+ taskQueue: 'llm-analytics-evals-task-queue',
+ workflowId: 'llma-trace-eval-eval-123-trace-abc',
+ workflowIdConflictPolicy: 'USE_EXISTING',
+ workflowIdReusePolicy: 'ALLOW_DUPLICATE_FAILED_ONLY',
+ workflowTaskTimeout: '2 minutes',
})
})
+ 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 }
+ )
+
+ expect(result).toBeNull()
+ })
+
it('produces the same workflow id for every event of the same trace', async () => {
- await service.startTraceEvaluationRunWorkflow(
+ await service.startAggregateEvaluationWorkflow(
'eval-123',
createMockEvent({ uuid: 'event-1' }),
'trace-789',
null,
- DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS
+ { strategy: 'fixed_window', window_seconds: 1800 }
)
- await service.startTraceEvaluationRunWorkflow(
+ await service.startAggregateEvaluationWorkflow(
'eval-123',
createMockEvent({ uuid: 'event-2' }),
'trace-789',
null,
- DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS
+ { strategy: 'fixed_window', window_seconds: 1800 }
)
const calls = (mockClient.workflow.start as jest.Mock).mock.calls
@@ -322,37 +342,40 @@ describe('TemporalService', () => {
expect(calls[0][1].workflowId).not.toContain('event-1')
})
- it('returns null when a completed run already exists for the trace', async () => {
- ;(mockClient.workflow.start as jest.Mock).mockRejectedValue(
- new WorkflowExecutionAlreadyStartedError('already started', 'wf-id', 'run-trace-evaluation')
- )
-
- const handle = await service.startTraceEvaluationRunWorkflow(
- 'eval-123',
- createMockEvent(),
- 'trace-789',
- null,
- DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS
- )
-
- expect(handle).toBeNull()
- })
-
it('rethrows non-dedup start failures', async () => {
;(mockClient.workflow.start as jest.Mock).mockRejectedValue(new Error('Temporal unavailable'))
await expect(
- service.startTraceEvaluationRunWorkflow(
- 'eval-123',
- createMockEvent(),
- 'trace-789',
- null,
- DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS
- )
+ service.startAggregateEvaluationWorkflow('eval-123', createMockEvent(), 'trace-789', null, {
+ strategy: 'fixed_window',
+ window_seconds: 1800,
+ })
).rejects.toThrow('Temporal unavailable')
})
})
+ 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 },
+ ],
+ [
+ { strategy: 'inactivity' as const },
+ { strategy: 'inactivity', quiet_period_seconds: 300, max_age_seconds: 7200 },
+ ],
+ [
+ { strategy: 'inactivity' as const, quiet_period_seconds: 60, max_age_seconds: 600 },
+ { strategy: 'inactivity', quiet_period_seconds: 60, max_age_seconds: 600 },
+ ],
+ ])('resolves %j', (input, expected) => {
+ expect(resolveSettleConfig(input)).toEqual(expected)
+ })
+ })
+
describe('workflowSafeTraceId', () => {
it('keeps short trace ids as-is', () => {
expect(workflowSafeTraceId('trace-789')).toBe('trace-789')
diff --git a/nodejs/src/ai-observability/services/temporal.service.ts b/nodejs/src/ai-observability/services/temporal.service.ts
index 3dc5a11d291d..6fc2d76e34f6 100644
--- a/nodejs/src/ai-observability/services/temporal.service.ts
+++ b/nodejs/src/ai-observability/services/temporal.service.ts
@@ -16,6 +16,7 @@ import { logger } from '~/common/utils/logger'
import { RawKafkaEvent } from '../../types'
import { AIObservabilityConfig } from '../config'
+import { EvaluationTargetConfig, ResolvedSettleConfig } from '../types'
export type TemporalServiceConfig = Pick<
AIObservabilityConfig,
@@ -49,10 +50,26 @@ function getEvaluationWorkflowPrefix(evaluationRuntime: EvaluationWorkflowRuntim
return EVALUATION_WORKFLOW_PREFIXES[evaluationRuntime]
}
-// Fallback aggregation window when an evaluation's target_config carries no window_seconds.
-// Per-eval values come from the eval config; this only applies to legacy/empty configs. Must
-// comfortably exceed a single LLM turn (seconds, or a few minutes with heavy tool usage).
+// Fallback settle values when an evaluation's target_config predates strategies or omits a
+// field. Per-eval values come from the eval config; these mirror the backend defaults in
+// products/ai_observability/backend/models/evaluation_configs.py.
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 {
+ 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,
+ }
+ }
+ return {
+ strategy: 'fixed_window',
+ window_seconds: targetConfig?.window_seconds ?? DEFAULT_TRACE_EVALUATION_WINDOW_SECONDS,
+ }
+}
const temporalWorkflowsStarted = new Counter({
name: 'evaluation_run_workflows_started',
@@ -211,28 +228,29 @@ export class TemporalService {
}
/**
- * Start (or join) the delayed whole-trace evaluation for (evaluation, trace).
+ * Start (or join) the settle-then-evaluate workflow for (evaluation, trace).
*
* The workflow id deliberately excludes the event uuid: the first matching generation of a
- * trace creates the workflow, and every later one lands on it as a no-op (USE_EXISTING
- * while pending/running). Once a run completed, ALLOW_DUPLICATE_FAILED_ONLY rejects new
- * starts — a trace is evaluated at most once per evaluation, which also caps the damage
- * from runaway shared trace ids ("0", "fixed_id", ...). Returns null when the trace was
- * already evaluated.
+ * 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.
*/
- async startTraceEvaluationRunWorkflow(
+ async startAggregateEvaluationWorkflow(
evaluationId: string,
event: RawKafkaEvent,
traceId: string,
sessionId: string | null,
- windowSeconds: number
+ settle: ResolvedSettleConfig
): Promise<WorkflowHandle | null> {
const client = await this.ensureConnected()
const workflowId = `llma-trace-eval-${evaluationId}-${workflowSafeTraceId(traceId)}`
try {
- const handle = await client.workflow.start('run-trace-evaluation', {
+ const handle = await client.workflow.start('run-aggregate-evaluation', {
args: [
{
evaluation_id: evaluationId,
@@ -240,7 +258,7 @@ export class TemporalService {
trace_id: traceId,
distinct_id: event.distinct_id,
session_id: sessionId,
- window_seconds: windowSeconds,
+ settle,
},
],
taskQueue: EVALUATION_TASK_QUEUE,
@@ -252,17 +270,16 @@ export class TemporalService {
temporalWorkflowsStarted.labels({ status: 'success' }).inc()
- logger.debug('Started trace evaluation run workflow', {
+ logger.debug('Started aggregate evaluation workflow', {
workflowId,
evaluationId,
traceId,
+ strategy: settle.strategy,
timestamp: event.timestamp,
})
return handle
} catch (error) {
- // A completed run for this (evaluation, trace) already exists — the expected
- // outcome for every matching event after the trace was evaluated.
if (error instanceof WorkflowExecutionAlreadyStartedError) {
temporalWorkflowsStarted.labels({ status: 'already_completed' }).inc()
return null
diff --git a/nodejs/src/ai-observability/types.ts b/nodejs/src/ai-observability/types.ts
index 46cd0acbd120..77ec89d11f3e 100644
--- a/nodejs/src/ai-observability/types.ts
+++ b/nodejs/src/ai-observability/types.ts
@@ -14,6 +14,21 @@ export type EvaluationStatusReason =
| 'model_not_found'
| 'hog_error'
export type EvaluationTarget = 'generation' | 'trace'
+export type EvaluationSettleStrategy = 'fixed_window' | 'inactivity'
+
+/** Settle config stored on the evaluation. Rows saved before strategies existed have no
+ * `strategy` key and mean 'fixed_window'. */
+export interface EvaluationTargetConfig {
+ strategy?: EvaluationSettleStrategy
+ window_seconds?: number
+ quiet_period_seconds?: number
+ max_age_seconds?: number
+}
+
+/** Fully-resolved settle config passed to the workflow (defaults applied, one shape per strategy). */
+export type ResolvedSettleConfig =
+ | { strategy: 'fixed_window'; window_seconds: number }
+ | { strategy: 'inactivity'; quiet_period_seconds: number; max_age_seconds: number }
export interface Evaluation {
id: string
@@ -29,8 +44,7 @@ export interface Evaluation {
output_config: Record<string, any>
conditions: EvaluationConditionSet[]
target: EvaluationTarget
- // Target-specific settings keyed off `target`. Trace targets carry the aggregation window.
- target_config: { window_seconds?: number }
+ target_config: EvaluationTargetConfig
provider_key_id?: string | null
created_at: string
updated_at: string
diff --git a/posthog/hogql/database/schema/ai_events.py b/posthog/hogql/database/schema/ai_events.py
index 4065be185c38..90d394197654 100644
--- a/posthog/hogql/database/schema/ai_events.py
+++ b/posthog/hogql/database/schema/ai_events.py
@@ -27,6 +27,15 @@ class AiEventsTable(Table):
"timestamp": DateTimeDatabaseField(
name="timestamp", nullable=False, description="When the event occurred (UTC)."
),
+ "_timestamp": DateTimeDatabaseField(
+ name="_timestamp",
+ nullable=False,
+ # Kafka-metadata column kept out of the serialized schema: internal ingestion-lag-aware
+ # checks need it, but it is not part of the user-facing ai_events surface.
+ hidden=True,
+ description="When this row was written to ClickHouse (Kafka consumer processing time, UTC). "
+ "Unlike `timestamp`, this is not client-set, so it's safe to use for ingestion-lag-aware checks.",
+ ),
"team_id": IntegerDatabaseField(name="team_id", nullable=False),
"distinct_id": StringDatabaseField(
name="distinct_id",
diff --git a/posthog/temporal/ai_observability/__init__.py b/posthog/temporal/ai_observability/__init__.py
index 376a6b007472..1a1acadfbede 100644
--- a/posthog/temporal/ai_observability/__init__.py
+++ b/posthog/temporal/ai_observability/__init__.py
@@ -42,6 +42,10 @@ from posthog.temporal.ai_observability.evaluation_workflow_activities import (
update_key_state_activity,
)
from posthog.temporal.ai_observability.metrics import EvalsMetricsInterceptor # noqa: F401
+from posthog.temporal.ai_observability.run_aggregate_evaluation import (
+ RunAggregateEvaluationWorkflow,
+ check_trace_settled_activity,
+)
from posthog.temporal.ai_observability.run_evaluation import RunEvaluationWorkflow
from posthog.temporal.ai_observability.run_tagger import (
RunTaggerWorkflow,
@@ -82,7 +86,8 @@ from products.signals.backend.temporal.emit_eval_signal import emit_eval_signal_
EVAL_WORKFLOWS = [
RunEvaluationWorkflow,
- RunTraceEvaluationWorkflow,
+ RunTraceEvaluationWorkflow, # drains in-flight runs; remove once none remain post-deploy
+ RunAggregateEvaluationWorkflow,
]
EVAL_ACTIVITIES = [
@@ -95,6 +100,7 @@ EVAL_ACTIVITIES = [
execute_sentiment_eval_activity,
execute_trace_llm_judge_activity,
execute_trace_hog_eval_activity,
+ check_trace_settled_activity,
emit_evaluation_event_activity,
emit_trace_evaluation_event_activity,
emit_internal_telemetry_activity,
diff --git a/posthog/temporal/ai_observability/metrics.py b/posthog/temporal/ai_observability/metrics.py
index 10fa4d6c34ef..5d22afec9379 100644
--- a/posthog/temporal/ai_observability/metrics.py
+++ b/posthog/temporal/ai_observability/metrics.py
@@ -32,6 +32,8 @@ EVAL_ACTIVITY_TYPES = {
"emit_internal_telemetry_activity",
"update_key_state_activity",
"emit_eval_signal_activity",
+ # check_trace_settled_activity is deliberately excluded: its expected trace_not_settled
+ # failures would otherwise count as activity errors.
}
EVAL_WORKFLOW_TYPES = {
@@ -102,6 +104,18 @@ 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).
+
+ 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")
+ counter.add(1)
+
+
def increment_eval_signal_outcome(outcome: str) -> None:
"""Track eval signal activity outcomes (skipped_config_disabled, skipped_org_not_approved, skipped_low_significance, emitted, summarization_failed)."""
meter = get_metric_meter({"outcome": outcome})
diff --git a/posthog/temporal/ai_observability/run_aggregate_evaluation.py b/posthog/temporal/ai_observability/run_aggregate_evaluation.py
new file mode 100644
index 000000000000..8536181bca2f
--- /dev/null
+++ b/posthog/temporal/ai_observability/run_aggregate_evaluation.py
@@ -0,0 +1,365 @@
+"""Aggregate evaluation workflow: a settling phase in front of the shared trace-evaluation body.
+
+Successor to `run-trace-evaluation`. The scheduler starts this workflow once per
+(evaluation, trace) pair on the first condition-matching generation. Under the fixed_window
+strategy the workflow just sleeps for the configured window, matching the old workflow's
+behavior exactly. Under inactivity it sleeps one quiet period, then polls
+`check_trace_settled_activity` — the activity itself raises a retryable error until the trace
+has gone quiet, so the activity's retry schedule *is* the poll loop — with the remaining
+max-age budget as the schedule-to-close timeout, which doubles as the hard cap on how long
+polling can run. Workflow id scheme and dedup policies are unchanged, so a trace is still
+evaluated at most once per evaluation.
+
+The old workflow stays registered until its in-flight runs drain (bounded by the 2h max
+window), then gets removed in a follow-up.
+"""
+
+import json
+import asyncio
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import temporalio
+from temporalio.common import RetryPolicy
+from temporalio.exceptions import ApplicationError
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+
+from posthog.clickhouse.client.connection import Workload
+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
+from posthog.temporal.ai_observability.evaluation_llm_judge import LLM_JUDGE_RETRY_POLICY
+from posthog.temporal.ai_observability.evaluation_workflow_activities import (
+ EmitInternalTelemetryInputs,
+ RunEvaluationInputs,
+ emit_internal_telemetry_activity,
+ fetch_evaluation_activity,
+)
+from posthog.temporal.ai_observability.metrics import increment_errors, increment_settle_poll
+from posthog.temporal.ai_observability.run_evaluation import (
+ WorkflowResult,
+ handle_llm_judge_activity_error,
+ handle_terminal_user_error_result,
+)
+from posthog.temporal.ai_observability.run_trace_evaluation import (
+ TRACE_EVENTS_LOOKBACK,
+ EmitTraceEvaluationEventInputs,
+ ExecuteTraceEvaluationInputs,
+ emit_trace_evaluation_event_activity,
+ execute_trace_hog_eval_activity,
+ execute_trace_llm_judge_activity,
+)
+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 (
+ TRACE_EVAL_DEFAULT_MAX_AGE_SECONDS,
+ TRACE_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
+ TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
+ TRACE_EVAL_MAX_MAX_AGE_SECONDS,
+ TRACE_EVAL_MAX_QUIET_PERIOD_SECONDS,
+ TRACE_EVAL_MAX_WINDOW_SECONDS,
+ TRACE_EVAL_MIN_MAX_AGE_SECONDS,
+ TRACE_EVAL_MIN_QUIET_PERIOD_SECONDS,
+ TRACE_EVAL_MIN_WINDOW_SECONDS,
+)
+
+INGESTION_LAG_MARGIN_SECONDS = 15
+
+# Structural trace activity only: $ai_evaluation / $ai_feedback / $ai_metric are post-hoc
+# annotations — another eval's verdict or late user feedback must not defer settling.
+_LIVENESS_EVENTS = ("$ai_generation", "$ai_span", "$ai_embedding", "$ai_trace")
+
+# ai_events only, never the events fallback: every AI event is double-written there for all
+# teams, and the fallback's events-table scan is orders of magnitude more expensive. The query
+# must also stay ungrouped: an ungrouped aggregate always returns exactly one row, so
+# query_ai_events's empty-result probe (which triggers the fallback) never fires.
+#
+# The date_from guard bounds by ARRIVAL time (_timestamp), not the client-set `timestamp`, so a
+# backdated event (clock skew, historical backfill) can't hide activity from the poll by landing
+# outside a timestamp-based window while still arriving now. The (team_id, trace_id) sort-key
+# prefix still does the pruning; _timestamp only filters in-scan within the trace's granules.
+_SETTLE_POLL_SQL = """
+SELECT maxOrNull(_timestamp) AS last_seen
+FROM posthog.ai_events AS ai_events
+WHERE event IN {liveness_events}
+ AND trace_id = {trace_id}
+ AND _timestamp >= {date_from}
+"""
+
+
+@dataclass
+class CheckTraceSettledInputs:
+ team_id: int
+ trace_id: str
+ quiet_period_seconds: int
+
+ @property
+ def properties_to_log(self) -> dict[str, Any]:
+ return {"team_id": self.team_id, "trace_id": self.trace_id}
+
+
+@close_db_connections
+def check_trace_settled_activity(inputs: CheckTraceSettledInputs) -> str:
+ """One settle probe. Raises the retryable `trace_not_settled` error until the trace 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)
+ result = query_ai_events(
+ query=parse_select(_SETTLE_POLL_SQL),
+ placeholders={
+ "liveness_events": ast.Constant(value=list(_LIVENESS_EVENTS)),
+ "trace_id": ast.Constant(value=inputs.trace_id),
+ "date_from": ast.Constant(value=datetime.now(UTC) - TRACE_EVENTS_LOOKBACK),
+ },
+ team=team,
+ query_type="TraceSettlePoll",
+ fall_back_to_events=False,
+ workload=Workload.OFFLINE,
+ )
+ last_seen = result.results[0][0] if result.results else None
+ if last_seen is None:
+ # 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")
+ 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")
+ raise ApplicationError(f"trace active {int(quiet_for)}s ago", type="trace_not_settled")
+ increment_settle_poll("settled")
+ return last_seen.isoformat()
+
+
+def _clamp(value: Any, floor: int, ceiling: int, default: int) -> int:
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
+ return default
+ return int(min(max(value, floor), ceiling))
+
+
+def resolve_settle_plan(settle: dict[str, Any] | None) -> 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.
+ """
+ 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,
+ )
+ 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,
+ )
+ return ("fixed_window", window, window)
+
+
+@dataclass
+class RunAggregateEvaluationInputs:
+ evaluation_id: str
+ team_id: int
+ trace_id: str
+ distinct_id: str
+ session_id: str | None = None
+ settle: dict[str, Any] | None = None
+
+ @property
+ def properties_to_log(self) -> dict[str, Any]:
+ """Properties for PostHogClientInterceptor error capture."""
+ return {
+ "evaluation_id": self.evaluation_id,
+ "team_id": self.team_id,
+ "trace_id": self.trace_id,
+ }
+
+
+def _is_schedule_to_close_timeout(error: temporalio.exceptions.ActivityError) -> bool:
+ cause = error.cause
+ return (
+ isinstance(cause, temporalio.exceptions.TimeoutError)
+ and cause.type == temporalio.exceptions.TimeoutType.SCHEDULE_TO_CLOSE
+ )
+
+
+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.
+ cause = error.cause
+ return isinstance(cause, ApplicationError) and cause.type == "trace_not_settled"
+
+
[email protected](name="run-aggregate-evaluation")
+class RunAggregateEvaluationWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> RunAggregateEvaluationInputs:
+ return RunAggregateEvaluationInputs(**json.loads(inputs[0]))
+
+ @temporalio.workflow.run
+ async def run(self, inputs: RunAggregateEvaluationInputs) -> WorkflowResult:
+ window_start = temporalio.workflow.now()
+
+ strategy, primary_seconds, max_age_seconds = resolve_settle_plan(inputs.settle)
+ 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.
+ initial_sleep_seconds = min(primary_seconds + INGESTION_LAG_MARGIN_SECONDS, max_age_seconds)
+ 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)
+ 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,
+ ),
+ )
+ 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)):
+ 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)
+
+ eval_start = temporalio.workflow.now()
+
+ evaluation = await temporalio.workflow.execute_activity(
+ fetch_evaluation_activity,
+ RunEvaluationInputs(evaluation_id=inputs.evaluation_id, event_data={"team_id": inputs.team_id}),
+ schedule_to_close_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ evaluation_type = evaluation.get("evaluation_type", "llm_judge")
+
+ # The evaluation may have been paused or deleted during the settle phase —
+ # bail out instead of running against config the user just turned off.
+ if evaluation["deleted"] or not evaluation["enabled"]:
+ disabled_result: WorkflowResult = {
+ "verdict": None,
+ "skipped": True,
+ "skip_reason": "evaluation_deleted" if evaluation["deleted"] else "evaluation_disabled",
+ "evaluation_id": inputs.evaluation_id,
+ "evaluation_type": evaluation_type,
+ }
+ return disabled_result
+
+ execute_inputs = ExecuteTraceEvaluationInputs(
+ evaluation=evaluation,
+ team_id=inputs.team_id,
+ trace_id=inputs.trace_id,
+ window_start=window_start.isoformat(),
+ )
+
+ if evaluation_type == "hog":
+ # Unlike single-event hog evals, this activity includes a ClickHouse fetch, so
+ # allow one retry for transient query failures (the bytecode is deterministic).
+ result = await temporalio.workflow.execute_activity(
+ execute_trace_hog_eval_activity,
+ execute_inputs,
+ schedule_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ else:
+ try:
+ result = await temporalio.workflow.execute_activity(
+ execute_trace_llm_judge_activity,
+ execute_inputs,
+ # > single-event judge timeout: the activity also fetches the trace from ClickHouse
+ schedule_to_close_timeout=timedelta(minutes=8),
+ retry_policy=LLM_JUDGE_RETRY_POLICY,
+ )
+ except temporalio.exceptions.ActivityError as e:
+ handled = await handle_llm_judge_activity_error(e, evaluation, evaluation_type)
+ if handled is not None:
+ return handled
+ raise
+
+ if is_terminal_user_error_result(result):
+ return await handle_terminal_user_error_result(
+ evaluation=evaluation,
+ evaluation_type=evaluation_type,
+ result=result,
+ )
+
+ try:
+ await temporalio.workflow.execute_activity(
+ emit_trace_evaluation_event_activity,
+ EmitTraceEvaluationEventInputs(
+ evaluation=evaluation,
+ team_id=inputs.team_id,
+ trace_id=inputs.trace_id,
+ distinct_id=inputs.distinct_id,
+ session_id=inputs.session_id,
+ result=result,
+ start_time=eval_start,
+ ),
+ schedule_to_close_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ except Exception:
+ increment_errors("emit_evaluation_event_failed", provider=result.get("provider"))
+ raise
+
+ if not result.get("skipped"):
+ await temporalio.workflow.execute_activity(
+ emit_internal_telemetry_activity,
+ EmitInternalTelemetryInputs(
+ evaluation=evaluation,
+ team_id=inputs.team_id,
+ result=result,
+ ),
+ schedule_to_close_timeout=timedelta(seconds=30),
+ )
+
+ workflow_result: WorkflowResult = {
+ "verdict": result["verdict"],
+ "reasoning": result["reasoning"],
+ "evaluation_id": evaluation["id"],
+ "evaluation_type": evaluation_type,
+ "is_byok": result.get("is_byok", False),
+ "skipped": result.get("skipped", False),
+ }
+ if result.get("skipped"):
+ skip_reason = result.get("skip_reason")
+ if skip_reason is not None:
+ workflow_result["skip_reason"] = skip_reason
+ return workflow_result
diff --git a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
new file mode 100644
index 000000000000..9a75ff06e277
--- /dev/null
+++ b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
@@ -0,0 +1,356 @@
+import uuid
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+
+from temporalio import activity
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from posthog.clickhouse.client import sync_execute
+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 (
+ CheckTraceSettledInputs,
+ RunAggregateEvaluationInputs,
+ RunAggregateEvaluationWorkflow,
+ check_trace_settled_activity,
+ resolve_settle_plan,
+)
+from posthog.temporal.ai_observability.run_trace_evaluation import (
+ EmitTraceEvaluationEventInputs,
+ ExecuteTraceEvaluationInputs,
+)
+
+
+def setup_data():
+ organization = Organization.objects.create(name="Test Org")
+ team = Team.objects.create(organization=organization, name="Test Team")
+ return {"organization": organization, "team": team}
+
+
+def _insert_ai_event(
+ *, team: Team, event: str, trace_id: str, arrival: datetime, event_timestamp: datetime | 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`.
+
+ `event_timestamp` controls the client-set `timestamp` column; it defaults to "now" so
+ callers that don't care about it get the old behavior of a fresh, unremarkable event.
+
+ `bulk_create_ai_events` (posthog/models/ai_events/test_util.py) can't do this: it derives
+ `_timestamp` from the same `timestamp` value it inserts, so tests that need to simulate
+ ingestion lag write directly against the columns AI_EVENTS_TABLE_BASE_SQL leaves without
+ a default.
+ """
+ sync_execute(
+ """
+ INSERT INTO sharded_ai_events (
+ uuid, event, timestamp, team_id, distinct_id, person_id, properties,
+ trace_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
+ )
+ """,
+ {
+ "uuid": str(uuid.uuid4()),
+ "event": event,
+ "timestamp": (event_timestamp or datetime.now(UTC)).strftime("%Y-%m-%d %H:%M:%S.%f"),
+ "team_id": team.id,
+ "distinct_id": "test-user",
+ "person_id": str(uuid.uuid4()),
+ "properties": "{}",
+ "trace_id": trace_id,
+ "_timestamp": arrival.strftime("%Y-%m-%d %H:%M:%S"),
+ },
+ flush=False,
+ )
+
+
+class TestResolveSettlePlan:
+ @pytest.mark.parametrize(
+ "settle,expected",
+ [
+ (None, ("fixed_window", 1800, 1800)),
+ ({}, ("fixed_window", 1800, 1800)),
+ ({"strategy": "fixed_window", "window_seconds": 60}, ("fixed_window", 60, 60)),
+ # Legacy sub-floor values are bumped to the floor (the old workflow only re-clamped the max).
+ ({"window_seconds": 0}, ("fixed_window", 10, 10)),
+ ({"window_seconds": 99999}, ("fixed_window", 7200, 7200)),
+ ({"strategy": "inactivity"}, ("inactivity", 300, 7200)),
+ (
+ {"strategy": "inactivity", "quiet_period_seconds": 120, "max_age_seconds": 600},
+ ("inactivity", 120, 600),
+ ),
+ # Sub-floor and above-ceiling quiet_period_seconds are clamped the same way as window_seconds.
+ ({"strategy": "inactivity", "quiet_period_seconds": 5}, ("inactivity", 10, 7200)),
+ ({"strategy": "inactivity", "quiet_period_seconds": 5000}, ("inactivity", 1800, 7200)),
+ # max_age below quiet period is coerced up so the loop's min() can't fire before one quiet period.
+ (
+ {"strategy": "inactivity", "quiet_period_seconds": 600, "max_age_seconds": 60},
+ ("inactivity", 600, 600),
+ ),
+ ({"strategy": "bogus", "window_seconds": 60}, ("fixed_window", 60, 60)),
+ ],
+ )
+ def test_resolves_and_clamps(self, settle, expected):
+ assert resolve_settle_plan(settle) == expected
+
+
+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")
+ return {
+ "id": inputs.evaluation_id,
+ "name": "Hog eval",
+ "evaluation_type": "hog",
+ "evaluation_config": {},
+ "output_type": "boolean",
+ "output_config": {},
+ "team_id": 1,
+ "enabled": True,
+ "deleted": False,
+ }
+
+ @activity.defn(name="execute_trace_hog_eval_activity")
+ async def mock_execute_trace_hog(inputs: ExecuteTraceEvaluationInputs) -> EvaluationActivityResult:
+ calls.append("execute")
+ return {"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False}
+
+ @activity.defn(name="emit_trace_evaluation_event_activity")
+ async def mock_emit(inputs: EmitTraceEvaluationEventInputs) -> None:
+ calls.append("emit")
+
+ @activity.defn(name="emit_internal_telemetry_activity")
+ async def mock_telemetry(inputs: Any) -> None:
+ calls.append("telemetry")
+
+ return [mock_fetch_evaluation, mock_execute_trace_hog, mock_emit, mock_telemetry]
+
+
+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,
+ )
+
+
+class TestRunAggregateEvaluationWorkflow:
+ @pytest.mark.asyncio
+ async def test_fixed_window_sleeps_then_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(),
+ ):
+ start = await env.get_current_time()
+ result = await env.client.execute_workflow(
+ RunAggregateEvaluationWorkflow.run,
+ _workflow_inputs({"strategy": "fixed_window", "window_seconds": 600}),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+ elapsed = (await env.get_current_time()) - start
+ assert calls == ["fetch", "execute", "emit", "telemetry"]
+ assert result["verdict"] is True
+ assert elapsed >= timedelta(seconds=600)
+ assert elapsed < timedelta(seconds=900)
+
+ @pytest.mark.asyncio
+ async def test_inactivity_settles_after_one_quiet_period_when_silent(self):
+ calls: list[str] = []
+
+ @activity.defn(name="check_trace_settled_activity")
+ async def mock_settles_immediately(inputs: CheckTraceSettledInputs) -> str:
+ return "2026-07-23T00:00:00+00:00"
+
+ 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), mock_settles_immediately],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ handle = await env.client.start_workflow(
+ RunAggregateEvaluationWorkflow.run,
+ _workflow_inputs({"strategy": "inactivity", "quiet_period_seconds": 300, "max_age_seconds": 7200}),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+ await handle.result()
+ # env.get_current_time() after an execute_activity call with a schedule-to-close
+ # timeout can skew forward to that timeout even once the activity has already
+ # succeeded; 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 == ["fetch", "execute", "emit", "telemetry"]
+ assert elapsed >= timedelta(seconds=300)
+ assert elapsed < timedelta(seconds=600)
+
+ @pytest.mark.asyncio
+ async def test_inactivity_settles_after_failed_polls(self):
+ calls: list[str] = []
+ poll_attempts = {"n": 0}
+
+ @activity.defn(name="check_trace_settled_activity")
+ async def mock_check_settled(inputs: CheckTraceSettledInputs) -> str:
+ poll_attempts["n"] += 1
+ if poll_attempts["n"] <= 2:
+ raise ApplicationError("still active", type="trace_not_settled")
+ return "2026-07-23T00:00:00+00:00"
+
+ 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), mock_check_settled],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ handle = await env.client.start_workflow(
+ RunAggregateEvaluationWorkflow.run,
+ _workflow_inputs({"strategy": "inactivity", "quiet_period_seconds": 300, "max_age_seconds": 7200}),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+ result = await handle.result()
+ # env.get_current_time() after a retried activity leaves a stale schedule-to-close
+ # timer that skews a second read; the server-recorded execution window doesn't.
+ 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 poll_attempts["n"] == 3
+ assert calls == ["fetch", "execute", "emit", "telemetry"]
+ assert result["verdict"] is True
+ # quiet sleep (300) + two retry intervals (2 x 75); generous upper bound for task latency
+ assert elapsed >= timedelta(seconds=450)
+ assert elapsed < timedelta(seconds=750)
+
+ @pytest.mark.asyncio
+ async def test_inactivity_max_age_cap_evaluates_despite_never_settling(self):
+ calls: list[str] = []
+
+ @activity.defn(name="check_trace_settled_activity")
+ async def mock_never_settled(inputs: CheckTraceSettledInputs) -> str:
+ raise ApplicationError("still active", type="trace_not_settled")
+
+ 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), mock_never_settled],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ handle = await env.client.start_workflow(
+ RunAggregateEvaluationWorkflow.run,
+ _workflow_inputs({"strategy": "inactivity", "quiet_period_seconds": 300, "max_age_seconds": 600}),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+ result = await handle.result()
+ 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 == ["fetch", "execute", "emit", "telemetry"]
+ assert result["verdict"] is True
+ # The trace never settles, so we wait out the full max-age window (600) before grading,
+ # rather than giving up early once the next poll would overrun the budget.
+ assert elapsed >= timedelta(seconds=600)
+ assert elapsed < timedelta(seconds=750)
+
+
+@freeze_time("2026-07-23T12:00:00Z")
+class TestCheckTraceSettledActivity:
+ @pytest.mark.django_db(transaction=True)
+ def test_settled_when_quiet_beyond_margin(self, setup_data):
+ team = setup_data["team"]
+ trace_id = f"t-settled-{uuid.uuid4()}"
+ _insert_ai_event(
+ team=team, event="$ai_generation", trace_id=trace_id, arrival=datetime.now(UTC) - timedelta(seconds=60)
+ )
+ result = check_trace_settled_activity(
+ CheckTraceSettledInputs(team_id=team.id, trace_id=trace_id, quiet_period_seconds=30)
+ )
+ assert result is not None
+
+ @pytest.mark.django_db(transaction=True)
+ def test_not_settled_when_recent_activity(self, setup_data):
+ team = setup_data["team"]
+ trace_id = f"t-live-{uuid.uuid4()}"
+ _insert_ai_event(
+ team=team, event="$ai_generation", trace_id=trace_id, arrival=datetime.now(UTC) - timedelta(seconds=5)
+ )
+ with pytest.raises(ApplicationError) as err:
+ check_trace_settled_activity(
+ CheckTraceSettledInputs(team_id=team.id, trace_id=trace_id, quiet_period_seconds=30)
+ )
+ assert err.value.type == "trace_not_settled"
+
+ @pytest.mark.django_db(transaction=True)
+ def test_null_visibility_is_not_settled(self, setup_data):
+ team = setup_data["team"]
+ trace_id = f"t-missing-{uuid.uuid4()}"
+ with pytest.raises(ApplicationError) as err:
+ check_trace_settled_activity(
+ CheckTraceSettledInputs(team_id=team.id, trace_id=trace_id, quiet_period_seconds=30)
+ )
+ assert err.value.type == "trace_not_settled"
+
+ @pytest.mark.django_db(transaction=True)
+ def test_annotation_events_do_not_defer_settling(self, setup_data):
+ team = setup_data["team"]
+ trace_id = f"t-annot-{uuid.uuid4()}"
+ _insert_ai_event(
+ team=team, event="$ai_generation", trace_id=trace_id, arrival=datetime.now(UTC) - timedelta(seconds=120)
+ )
+ _insert_ai_event(
+ team=team, event="$ai_evaluation", trace_id=trace_id, arrival=datetime.now(UTC) - timedelta(seconds=2)
+ )
+ assert (
+ check_trace_settled_activity(
+ CheckTraceSettledInputs(team_id=team.id, trace_id=trace_id, quiet_period_seconds=30)
+ )
+ is not None
+ )
+
+ @pytest.mark.django_db(transaction=True)
+ def test_backdated_client_timestamp_still_counts_as_activity(self, setup_data):
+ team = setup_data["team"]
+ trace_id = f"t-backdated-{uuid.uuid4()}"
+ _insert_ai_event(
+ team=team,
+ event="$ai_generation",
+ trace_id=trace_id,
+ arrival=datetime.now(UTC) - timedelta(seconds=5),
+ event_timestamp=datetime.now(UTC) - timedelta(days=3),
+ )
+ with pytest.raises(ApplicationError) as err:
+ check_trace_settled_activity(
+ CheckTraceSettledInputs(team_id=team.id, trace_id=trace_id, quiet_period_seconds=30)
+ )
+ # Must be the "seen recently" not-settled path, not the "nothing visible" NULL path —
+ # 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
diff --git a/posthog/temporal/common/posthog_client.py b/posthog/temporal/common/posthog_client.py
index 016c55c998ed..53255e422cc1 100644
--- a/posthog/temporal/common/posthog_client.py
+++ b/posthog/temporal/common/posthog_client.py
@@ -23,6 +23,10 @@ from posthog.temporal.common.shutdown import WorkerShuttingDownError
logger = get_write_only_logger()
+# ApplicationError types that are expected control flow (e.g. activity-retry-as-poll
+# probes), not defects — same reasoning as the EgressBudgetExhausted exemption below.
+EXPECTED_CONTROL_FLOW_ERROR_TYPES = frozenset({"trace_not_settled"})
+
def _tag_team_id_on_current_span(input: ExecuteActivityInput | ExecuteWorkflowInput) -> None:
"""Tag the active span (the Temporal RunActivity/RunWorkflow span, when OTel tracing is
@@ -72,12 +76,18 @@ class _PostHogClientActivityInboundInterceptor(ActivityInboundInterceptor):
# Cancellations (worker drain, activity timeout, workflow cancellation), a cooperative
# worker shutdown (raised mid-activity during a deploy, always retried on a fresh
# worker), our own egress-budget backpressure (a deliberate "defer and retry later"
- # signal that our rate limiter already records via record_outbound_decision), and errors
+ # signal that our rate limiter already records via record_outbound_decision), errors
# explicitly marked non-reportable (expected customer/upstream conditions, e.g. a REST
- # API serving a login page instead of JSON) are expected control flow, not defects —
- # re-raise without reporting them to error tracking.
- if temporalio.exceptions.is_cancelled_exception(e) or isinstance(
- e, EgressBudgetExhausted | WorkerShuttingDownError | NonReportableError
+ # API serving a login page instead of JSON), and expected-control-flow ApplicationErrors
+ # (activity-retry-as-poll probes) are not defects — re-raise without reporting them to
+ # error tracking.
+ if (
+ temporalio.exceptions.is_cancelled_exception(e)
+ or isinstance(e, EgressBudgetExhausted | WorkerShuttingDownError | NonReportableError)
+ or (
+ isinstance(e, temporalio.exceptions.ApplicationError)
+ and e.type in EXPECTED_CONTROL_FLOW_ERROR_TYPES
+ )
):
raise
activity_info = activity.info()
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index ab56b8552462..776c90ae23b9 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -37,8 +37,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,
TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
+ TRACE_EVAL_MAX_MAX_AGE_SECONDS,
+ TRACE_EVAL_MAX_QUIET_PERIOD_SECONDS,
TRACE_EVAL_MAX_WINDOW_SECONDS,
+ TRACE_EVAL_MIN_MAX_AGE_SECONDS,
+ TRACE_EVAL_MIN_QUIET_PERIOD_SECONDS,
TRACE_EVAL_MIN_WINDOW_SECONDS,
EvaluationType,
evaluation_supports_reports,
@@ -124,21 +130,63 @@ class _OutputConfigField(serializers.JSONField):
@extend_schema_field(
{
- "type": "object",
- "properties": {
- "window_seconds": {
- "type": "integer",
- "description": (
- "For 'trace' target: seconds to wait after the first matching generation before "
- "evaluating the whole trace. Captured when the run is scheduled — editing it does not "
- "change trace runs already in flight."
- ),
- "minimum": TRACE_EVAL_MIN_WINDOW_SECONDS,
- "maximum": TRACE_EVAL_MAX_WINDOW_SECONDS,
- "default": TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
- }
- },
- "additionalProperties": False,
+ "oneOf": [
+ {
+ "type": "object",
+ "title": "Fixed window settle config",
+ "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."
+ ),
+ "minimum": TRACE_EVAL_MIN_WINDOW_SECONDS,
+ "maximum": TRACE_EVAL_MAX_WINDOW_SECONDS,
+ "default": TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
+ },
+ },
+ "additionalProperties": False,
+ },
+ {
+ "type": "object",
+ "title": "Inactivity settle config",
+ "required": ["strategy"],
+ "properties": {
+ "strategy": {
+ "type": "string",
+ "enum": ["inactivity"],
+ "description": "Evaluate once the trace 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,
+ },
+ "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."
+ ),
+ "minimum": TRACE_EVAL_MIN_MAX_AGE_SECONDS,
+ "maximum": TRACE_EVAL_MAX_MAX_AGE_SECONDS,
+ "default": TRACE_EVAL_DEFAULT_MAX_AGE_SECONDS,
+ },
+ },
+ "additionalProperties": False,
+ },
+ ],
+ "discriminator": {"propertyName": "strategy"},
}
)
class _TargetConfigField(serializers.JSONField):
@@ -231,7 +279,11 @@ class EvaluationSerializer(serializers.ModelSerializer):
)
target_config = _TargetConfigField(
required=False,
- help_text="Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.",
+ 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'."
+ ),
)
conditions = EvaluationConditionSerializer(
many=True,
@@ -298,7 +350,8 @@ class EvaluationSerializer(serializers.ModelSerializer):
"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."
+ "generations matches, and sampling applies per trace. When and how the trace run fires is "
+ "controlled by target_config's settle strategy."
)
},
"deleted": {"help_text": "Set to true to soft-delete the evaluation."},
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index 9f0f0a5241a3..97077168cd94 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -176,7 +176,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(response.json()["target"], "trace")
evaluation = Evaluation.objects.get(name="Trace target")
self.assertEqual(evaluation.target, "trace")
- self.assertEqual(evaluation.target_config, {"window_seconds": 30 * 60})
+ self.assertEqual(evaluation.target_config, {"strategy": "fixed_window", "window_seconds": 30 * 60})
self.assertEqual(EvaluationReport.objects.filter(evaluation=evaluation).count(), 1)
def test_trace_target_accepts_custom_window(self):
@@ -196,7 +196,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- self.assertEqual(response.json()["target_config"], {"window_seconds": 120})
+ self.assertEqual(response.json()["target_config"], {"strategy": "fixed_window", "window_seconds": 120})
def test_rejects_window_below_minimum(self):
response = self.client.post(
@@ -255,6 +255,64 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["attr"], "target_config")
+ def test_create_trace_evaluation_with_inactivity_strategy(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/",
+ {
+ "name": "Inactivity eval",
+ "evaluation_type": "hog",
+ "evaluation_config": {"source": "return true"},
+ "output_type": "boolean",
+ "target": "trace",
+ "target_config": {"strategy": "inactivity", "quiet_period_seconds": 120},
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ self.assertEqual(
+ response.json()["target_config"],
+ {"strategy": "inactivity", "quiet_period_seconds": 120, "max_age_seconds": 7200},
+ )
+
+ def test_inactivity_strategy_rejects_max_age_below_quiet_period(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/",
+ {
+ "name": "Bad inactivity eval",
+ "evaluation_type": "hog",
+ "evaluation_config": {"source": "return true"},
+ "output_type": "boolean",
+ "target": "trace",
+ "target_config": {"strategy": "inactivity", "quiet_period_seconds": 600, "max_age_seconds": 300},
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["attr"], "target_config")
+
+ def test_switching_strategy_replaces_settle_config(self):
+ evaluation = Evaluation.objects.create(
+ name="Trace target",
+ evaluation_type="hog",
+ evaluation_config={"source": "return true"},
+ output_type="boolean",
+ target="trace",
+ target_config={"strategy": "fixed_window", "window_seconds": 30 * 60},
+ team=self.team,
+ created_by=self.user,
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/",
+ {"target_config": {"strategy": "inactivity"}},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ response.json()["target_config"],
+ {"strategy": "inactivity", "quiet_period_seconds": 300, "max_age_seconds": 7200},
+ )
+
def test_rejects_invalid_target(self):
response = self.client.post(
f"/api/environments/{self.team.id}/evaluations/",
@@ -950,6 +1008,21 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
self.assertEqual(response.data["conditions"][0]["rollout_percentage"], rollout_percentage)
+ @parameterized.expand([(["a", "b"],), ("trace",), (5,)])
+ def test_non_dict_target_config_returns_400(self, bad_config):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/",
+ {
+ "name": "Bad config eval",
+ "evaluation_type": "hog",
+ "evaluation_config": {"source": "return true"},
+ "output_type": "boolean",
+ "target": "trace",
+ "target_config": bad_config,
+ },
+ )
+ self.assertEqual(response.status_code, 400)
+
class TestTestHogEndpoint(APIBaseTest):
EVENT_TIMESTAMP = "2026-07-20T12:34:56Z"
diff --git a/products/ai_observability/backend/models/evaluation_configs.py b/products/ai_observability/backend/models/evaluation_configs.py
index 3ea963b385ac..d6fee708aed1 100644
--- a/products/ai_observability/backend/models/evaluation_configs.py
+++ b/products/ai_observability/backend/models/evaluation_configs.py
@@ -1,8 +1,8 @@
-from typing import Any, Literal
+from typing import Annotated, Any, Literal
from django.db import models
-from pydantic import BaseModel, ConfigDict, Field, field_validator
+from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, field_validator, model_validator
class EvaluationType(models.TextChoices):
@@ -66,42 +66,86 @@ class SentimentOutputConfig(BaseModel):
"""Configuration for sentiment output type."""
-# Trace-target aggregation window: how long to wait after the first matching generation before
-# pulling the whole trace and evaluating it. The default is intentionally generous — even heavy
-# tool-using turns settle well under it — while the floor stays low so local testing doesn't
-# require waiting half an hour. The workflow re-clamps to the same ceiling as a safety net.
+# Settle-strategy bounds for trace-target evaluations. fixed_window: wait this long after the
+# first matching generation, then evaluate. inactivity: evaluate once the trace has had no new activity
+# for the quiet period, with max_age bounding the total wait from the first one.
+# Defaults are generous so heavy tool-using turns settle; floors keep local testing fast; the
+# 2h ceiling bounds how long a workflow sleeps. The workflow re-clamps as a safety net.
TRACE_EVAL_DEFAULT_WINDOW_SECONDS = 30 * 60
TRACE_EVAL_MIN_WINDOW_SECONDS = 10
TRACE_EVAL_MAX_WINDOW_SECONDS = 2 * 60 * 60
EVALUATION_TEST_LOOKBACK_DAYS = 7
+TRACE_EVAL_DEFAULT_QUIET_PERIOD_SECONDS = 5 * 60
+TRACE_EVAL_MIN_QUIET_PERIOD_SECONDS = 10
+TRACE_EVAL_MAX_QUIET_PERIOD_SECONDS = 30 * 60
-class TraceTargetConfig(BaseModel):
- """Configuration for trace-target evaluations."""
+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
+
+
+class FixedWindowSettleConfig(BaseModel):
+ """Wait a fixed window after the first matching generation, then evaluate."""
model_config = ConfigDict(extra="forbid")
+ strategy: Literal["fixed_window"] = "fixed_window"
window_seconds: int = Field(
default=TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
ge=TRACE_EVAL_MIN_WINDOW_SECONDS,
le=TRACE_EVAL_MAX_WINDOW_SECONDS,
- description="Seconds to wait after the first matching generation before evaluating the whole trace.",
+ description="Seconds to wait after the first matching generation before evaluating.",
)
+class InactivitySettleConfig(BaseModel):
+ """Evaluate once the trace has had no new activity for the quiet period."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ strategy: Literal["inactivity"]
+ quiet_period_seconds: int = Field(
+ default=TRACE_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
+ ge=TRACE_EVAL_MIN_QUIET_PERIOD_SECONDS,
+ le=TRACE_EVAL_MAX_QUIET_PERIOD_SECONDS,
+ description="Seconds without new trace activity before the unit counts as settled.",
+ )
+ max_age_seconds: int = Field(
+ default=TRACE_EVAL_DEFAULT_MAX_AGE_SECONDS,
+ ge=TRACE_EVAL_MIN_MAX_AGE_SECONDS,
+ le=TRACE_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) -> "InactivitySettleConfig":
+ 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
+
+
+SettleConfig = Annotated[FixedWindowSettleConfig | InactivitySettleConfig, Field(discriminator="strategy")]
+
+_SETTLE_CONFIG_ADAPTER: TypeAdapter[FixedWindowSettleConfig | InactivitySettleConfig] = TypeAdapter(SettleConfig)
+
+
def validate_target_config(target: str, target_config: dict) -> dict:
"""Validate target_config based on target.
- Trace targets carry a `{window_seconds}` config (defaulted when absent). Every other target
- (generation today) carries no config, so its bag is normalized to empty — this also strips a
- stale window if a user switches a trace eval back to generation.
+ 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.
"""
- if target == "trace":
- try:
- return TraceTargetConfig(**(target_config or {})).model_dump()
- except Exception as e:
- raise ValueError(f"Invalid target_config for trace: {str(e)}") from e
- return {}
+ if target != "trace":
+ return {}
+ try:
+ config = {**(target_config or {})}
+ config.setdefault("strategy", "fixed_window")
+ return _SETTLE_CONFIG_ADAPTER.validate_python(config).model_dump()
+ except Exception as e:
+ raise ValueError(f"Invalid target_config for trace: {str(e)}") from e
# Mapping: (evaluation_type, output_type) -> (evaluation_config_model, output_config_model)
diff --git a/products/ai_observability/backend/models/test/test_evaluation_configs.py b/products/ai_observability/backend/models/test/test_evaluation_configs.py
new file mode 100644
index 000000000000..196e95bd9b5e
--- /dev/null
+++ b/products/ai_observability/backend/models/test/test_evaluation_configs.py
@@ -0,0 +1,50 @@
+import pytest
+
+from products.ai_observability.backend.models.evaluation_configs import validate_target_config
+
+
+class TestValidateTargetConfig:
+ @pytest.mark.parametrize(
+ "config,expected",
+ [
+ ({}, {"strategy": "fixed_window", "window_seconds": 1800}),
+ (None, {"strategy": "fixed_window", "window_seconds": 1800}),
+ ({"window_seconds": 60}, {"strategy": "fixed_window", "window_seconds": 60}),
+ (
+ {"strategy": "fixed_window", "window_seconds": 7200},
+ {"strategy": "fixed_window", "window_seconds": 7200},
+ ),
+ (
+ {"strategy": "inactivity"},
+ {"strategy": "inactivity", "quiet_period_seconds": 300, "max_age_seconds": 7200},
+ ),
+ (
+ {"strategy": "inactivity", "quiet_period_seconds": 60, "max_age_seconds": 600},
+ {"strategy": "inactivity", "quiet_period_seconds": 60, "max_age_seconds": 600},
+ ),
+ ],
+ )
+ def test_trace_configs_normalize(self, config, expected):
+ assert validate_target_config("trace", config) == expected
+
+ @pytest.mark.parametrize(
+ "config",
+ [
+ {"window_seconds": 5},
+ {"window_seconds": 7201},
+ {"strategy": "inactivity", "quiet_period_seconds": 5},
+ {"strategy": "inactivity", "quiet_period_seconds": 1801},
+ {"strategy": "inactivity", "max_age_seconds": 30},
+ {"strategy": "inactivity", "quiet_period_seconds": 600, "max_age_seconds": 300},
+ {"strategy": "inactivity", "window_seconds": 100},
+ {"strategy": "fixed_window", "quiet_period_seconds": 100},
+ {"strategy": "sliding"},
+ {"unknown_key": 1},
+ ],
+ )
+ def test_invalid_trace_configs_rejected(self, config):
+ with pytest.raises(ValueError):
+ validate_target_config("trace", config)
+
+ def test_generation_strips_config(self):
+ assert validate_target_config("generation", {"strategy": "inactivity"}) == {}
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index e7e34b3e824c..a49433036254 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -21,7 +21,9 @@ import {
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { DurationPicker } from 'lib/components/DurationPicker/DurationPicker'
import { NotFound } from 'lib/components/NotFound'
+import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { SceneExport } from 'scenes/sceneTypes'
import { SceneBreadcrumbBackButton } from '~/layout/scenes/components/SceneBreadcrumbs'
@@ -49,9 +51,15 @@ import {
isBooleanEvaluationOutput,
} from './evaluationCapabilities'
import { evaluationReportLogic } from './evaluationReportLogic'
-import { DEFAULT_TRACE_WINDOW_SECONDS, LLMEvaluationLogicProps, llmEvaluationLogic } from './llmEvaluationLogic'
+import {
+ DEFAULT_TRACE_MAX_AGE_SECONDS,
+ DEFAULT_TRACE_QUIET_PERIOD_SECONDS,
+ DEFAULT_TRACE_WINDOW_SECONDS,
+ LLMEvaluationLogicProps,
+ llmEvaluationLogic,
+} from './llmEvaluationLogic'
import { statusReasonLabel, statusReasonRecoveryLabel } from './statusDisplay'
-import { EvaluationTarget, EvaluationType } from './types'
+import { EvaluationSettleStrategy, EvaluationTarget, EvaluationType } from './types'
export function AIObservabilityEvaluation(): JSX.Element {
const {
@@ -70,6 +78,8 @@ export function AIObservabilityEvaluation(): JSX.Element {
modelSelectionRequired,
} = useValues(llmEvaluationLogic)
const { searchParams } = useValues(router)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const settlingStrategyEnabled = !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVAL_SETTLING_STRATEGY]
const {
setEvaluationName,
setEvaluationDescription,
@@ -79,7 +89,8 @@ export function AIObservabilityEvaluation(): JSX.Element {
resetEvaluation,
setEvaluationType,
setEvaluationTarget,
- setTraceWindowSeconds,
+ setSettleStrategy,
+ patchTargetConfig,
setActiveTab,
} = useActions(llmEvaluationLogic)
const { push } = useActions(router)
@@ -104,6 +115,9 @@ 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 isReportableEvaluation = evaluationSupportsReports(evaluation)
const supportsRunSummary = evaluationSupportsRunSummary(evaluation)
const isBooleanOutput = isBooleanEvaluationOutput(evaluation.output_type)
@@ -495,27 +509,111 @@ export function AIObservabilityEvaluation(): JSX.Element {
</Field>
<p className="text-muted text-sm -mt-2">
{evaluation.target === 'trace'
- ? 'Runs once per trace on all of its events together, after a delay that lets the trace complete.'
+ ? 'Runs 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' && (
- <Field name="trace_window" label="Wait before evaluating">
- <div className="space-y-1">
- <DurationPicker
- value={
- evaluation.target_config.window_seconds ??
- DEFAULT_TRACE_WINDOW_SECONDS
- }
- onChange={setTraceWindowSeconds}
- />
- <p className="text-muted text-xs">
- How long to wait after the first matching generation
- before pulling the whole trace (10s–2h). Captured
- when the run is scheduled — changing it won't affect
- trace runs already in flight.
- </p>
- </div>
- </Field>
+ <>
+ {settlingStrategyEnabled && (
+ <Field name="settle_strategy" label="Evaluate when">
+ <LemonSelect<EvaluationSettleStrategy>
+ value={effectiveStrategy}
+ onChange={setSettleStrategy}
+ options={[
+ {
+ value: 'fixed_window',
+ label: 'A fixed delay has passed',
+ },
+ {
+ value: 'inactivity',
+ label: 'The trace goes quiet',
+ },
+ ]}
+ fullWidth
+ />
+ </Field>
+ )}
+ {effectiveStrategy === 'fixed_window' ? (
+ <Field
+ name="settle_window"
+ label="Wait before evaluating"
+ >
+ <div className="space-y-1">
+ <DurationPicker
+ value={
+ evaluation.target_config
+ .window_seconds ??
+ DEFAULT_TRACE_WINDOW_SECONDS
+ }
+ onChange={(value) => {
+ if (
+ evaluation.target_config
+ .strategy === 'inactivity'
+ ) {
+ setSettleStrategy('fixed_window')
+ }
+ patchTargetConfig({
+ window_seconds: value,
+ })
+ }}
+ />
+ <p className="text-muted text-xs">
+ How long to wait after the first matching
+ generation before pulling the whole trace
+ (10s–2h). Captured when the run is scheduled
+ — changing it won't affect trace runs
+ already in flight.
+ </p>
+ </div>
+ </Field>
+ ) : (
+ <>
+ <Field
+ name="settle_quiet_period"
+ label="Quiet period"
+ >
+ <div className="space-y-1">
+ <DurationPicker
+ value={
+ evaluation.target_config
+ .quiet_period_seconds ??
+ DEFAULT_TRACE_QUIET_PERIOD_SECONDS
+ }
+ onChange={(value) =>
+ patchTargetConfig({
+ quiet_period_seconds: value,
+ })
+ }
+ />
+ <p className="text-muted text-xs">
+ Evaluate once the trace has had no new
+ activity for this long (10s–30m).
+ </p>
+ </div>
+ </Field>
+ <Field name="settle_max_age" label="Evaluate by">
+ <div className="space-y-1">
+ <DurationPicker
+ value={
+ evaluation.target_config
+ .max_age_seconds ??
+ DEFAULT_TRACE_MAX_AGE_SECONDS
+ }
+ onChange={(value) =>
+ patchTargetConfig({
+ max_age_seconds: value,
+ })
+ }
+ />
+ <p className="text-muted text-xs">
+ 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/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index 975013348a49..4fe54dad569b 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -400,6 +400,68 @@ return result`,
}),
})
})
+
+ it('seeds a fixed window settle config when switching target to trace', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+
+ logic.actions.setEvaluationTarget('trace')
+
+ expect(logic.values.evaluation?.target_config).toEqual({
+ strategy: 'fixed_window',
+ window_seconds: 30 * 60,
+ })
+ })
+
+ it('seeds inactivity defaults when switching settle strategy', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+
+ logic.actions.setEvaluationTarget('trace')
+ logic.actions.setSettleStrategy('inactivity')
+
+ expect(logic.values.evaluation?.target_config).toEqual({
+ strategy: 'inactivity',
+ quiet_period_seconds: 5 * 60,
+ max_age_seconds: 2 * 60 * 60,
+ })
+ })
+
+ it('patches a single settle field without clobbering the rest', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+
+ logic.actions.setEvaluationTarget('trace')
+ logic.actions.setSettleStrategy('inactivity')
+ logic.actions.patchTargetConfig({ quiet_period_seconds: 60 })
+
+ expect(logic.values.evaluation?.target_config).toEqual({
+ strategy: 'inactivity',
+ quiet_period_seconds: 60,
+ max_age_seconds: 2 * 60 * 60,
+ })
+ })
+
+ it('reseeds the fixed window when switching strategy back', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+
+ logic.actions.setEvaluationTarget('trace')
+ logic.actions.setSettleStrategy('inactivity')
+ logic.actions.setSettleStrategy('fixed_window')
+
+ expect(logic.values.evaluation?.target_config).toEqual({
+ strategy: 'fixed_window',
+ window_seconds: 30 * 60,
+ })
+ })
+
+ it('reseeding fixed window over an inactivity bag leaves no inactivity keys', () => {
+ logic.actions.setEvaluationTarget('trace')
+ logic.actions.setSettleStrategy('inactivity')
+ logic.actions.setSettleStrategy('fixed_window')
+ logic.actions.patchTargetConfig({ window_seconds: 900 })
+ expect(logic.values.evaluation?.target_config).toEqual({
+ strategy: 'fixed_window',
+ window_seconds: 900,
+ })
+ })
})
describe('selectors', () => {
@@ -1313,7 +1375,7 @@ return result`,
logic.actions.setEvaluationType('hog')
logic.actions.setEvaluationTarget('trace')
- logic.actions.setTraceWindowSeconds(120)
+ logic.actions.patchTargetConfig({ window_seconds: 120 })
logic.actions.testHogOnSample()
await expectLogic(logic)
@@ -1326,7 +1388,7 @@ return result`,
target_config: { window_seconds: 120 },
})
- logic.actions.setTraceWindowSeconds(240)
+ logic.actions.patchTargetConfig({ window_seconds: 240 })
await expectLogic(logic).toMatchValues({ hogTestResults: null })
})
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index b90222ed14d0..6a1bc2d85f78 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -39,9 +39,11 @@ import type {
EvaluationConditionSet,
EvaluationConfig,
EvaluationRun,
+ EvaluationSettleStrategy,
EvaluationSummary,
EvaluationSummaryFilter,
EvaluationTarget,
+ EvaluationTargetConfig,
EvaluationType,
HogEvaluation,
LLMJudgeEvaluation,
@@ -49,9 +51,11 @@ import type {
SentimentEvaluation,
} from './types'
-// Mirrors TRACE_EVAL_DEFAULT_WINDOW_SECONDS on the backend — the value pre-filled when an
-// evaluation is switched to the trace target. The backend re-defaults and clamps regardless.
+// Mirror the backend defaults in evaluation_configs.py — pre-filled when a strategy is
+// selected. The backend re-defaults and clamps regardless.
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_HOG_SOURCE = getHogEvalExample('output_not_empty').source
@@ -270,6 +274,9 @@ export interface llmEvaluationLogicActions {
runsStats: EvaluationRunsStats | null
payload?: any
}
+ patchTargetConfig: (patch: Partial<Omit<EvaluationTargetConfig, 'strategy'>>) => {
+ patch: Partial<Omit<EvaluationTargetConfig, 'strategy'>>
+ }
refreshEvaluationRuns: () => {
value: true
}
@@ -332,8 +339,8 @@ export interface llmEvaluationLogicActions {
setModelConfiguration: (modelConfiguration: ModelConfiguration | null) => {
modelConfiguration: ModelConfiguration | null
}
- setTraceWindowSeconds: (windowSeconds: number) => {
- windowSeconds: number
+ setSettleStrategy: (strategy: EvaluationSettleStrategy) => {
+ strategy: EvaluationSettleStrategy
}
setTriggerConditions: (conditions: EvaluationConditionSet[]) => {
conditions: EvaluationConditionSet[]
@@ -445,7 +452,10 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
setModelConfiguration: (modelConfiguration: ModelConfiguration | null) => ({ modelConfiguration }),
setEvaluationType: (evaluationType: EvaluationType) => ({ evaluationType }),
setEvaluationTarget: (target: EvaluationTarget) => ({ target }),
- setTraceWindowSeconds: (windowSeconds: number) => ({ windowSeconds }),
+ setSettleStrategy: (strategy: EvaluationSettleStrategy) => ({ strategy }),
+ // Duration fields only — switching strategy must go through setSettleStrategy so the
+ // bag is fully reseeded (the strategies carry disjoint fields).
+ patchTargetConfig: (patch: Partial<Omit<EvaluationTargetConfig, 'strategy'>>) => ({ patch }),
setHogSource: (source: string) => ({ source }),
// Tab navigation
@@ -655,9 +665,12 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
if (!state) {
return null
}
- // Seed the window when switching to trace so the field shows a sane default;
- // clear the bag when switching back so we don't persist a stale window.
- const target_config = target === 'trace' ? { window_seconds: DEFAULT_TRACE_WINDOW_SECONDS } : {}
+ // 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 }
+ : {}
if (
state.evaluation_type === 'hog' &&
LEGACY_HOG_DEFAULT_SOURCES.includes(state.evaluation_config.source)
@@ -671,10 +684,24 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
}
return { ...state, target, target_config }
},
- setTraceWindowSeconds: (state, { windowSeconds }) =>
- state
- ? { ...state, target_config: { ...state.target_config, window_seconds: windowSeconds } }
- : null,
+ setSettleStrategy: (state, { strategy }) => {
+ if (!state || state.target !== 'trace') {
+ 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 }
+ },
+ patchTargetConfig: (state, { patch }) =>
+ state ? { ...state, target_config: { ...state.target_config, ...patch } } : null,
setHogSource: (state, { source }) =>
state && state.evaluation_type === 'hog'
? { ...state, evaluation_config: { ...state.evaluation_config, source } }
@@ -689,7 +716,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
setEvaluationTarget: () => null,
setEvaluationType: () => null,
setHogSource: () => null,
- setTraceWindowSeconds: () => null,
+ setSettleStrategy: () => null,
+ patchTargetConfig: () => null,
setTriggerConditions: () => null,
},
selectedModel: [
@@ -743,7 +771,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
setModelConfiguration: () => true,
setEvaluationType: () => true,
setEvaluationTarget: () => true,
- setTraceWindowSeconds: () => true,
+ setSettleStrategy: () => true,
+ patchTargetConfig: () => true,
setHogSource: () => true,
saveEvaluationSuccess: () => false,
loadEvaluationSuccess: () => false,
diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.ts
index 7001811131fc..160c15d39ae3 100644
--- a/products/ai_observability/frontend/evaluations/types.ts
+++ b/products/ai_observability/frontend/evaluations/types.ts
@@ -11,6 +11,7 @@ import { LLMProvider } from '../settings/llmProviderKeysLogic'
export type EvaluationType = 'llm_judge' | 'hog' | 'sentiment'
export type EvaluationTarget = 'generation' | 'trace'
+export type EvaluationSettleStrategy = 'fixed_window' | 'inactivity'
export type EvaluationOutputType = 'boolean' | 'sentiment'
export type EvaluationStatus = 'active' | 'paused' | 'error'
export type EvaluationStatusReason =
@@ -35,9 +36,16 @@ export interface EvaluationOutputConfig {
allows_na?: boolean
}
+/** Settle config for aggregate targets. Rows saved before strategies existed have no
+ * `strategy` key and mean 'fixed_window'. */
export interface EvaluationTargetConfig {
- /** For 'trace' target: seconds to wait after the first matching generation before evaluating the trace. */
+ 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. */
+ quiet_period_seconds?: number
+ /** inactivity: hard cap in seconds on the total wait from the first matching generation. */
+ max_age_seconds?: number
}
export interface LLMJudgeEvaluationConfig {
@@ -66,7 +74,7 @@ export interface BaseEvaluationConfig {
conditions: EvaluationConditionSet[]
/** What the evaluation runs on: each matching generation event, or the whole trace once. */
target: EvaluationTarget
- /** Target-specific settings. For 'trace': {window_seconds}. Empty for 'generation'. */
+ /** Target-specific settings — see EvaluationTargetConfig. Empty for 'generation'. */
target_config: EvaluationTargetConfig
model_configuration: ModelConfiguration | null
total_runs: number
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index c13c2d56bee4..d366f36c0020 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -533,16 +533,35 @@ export type EvaluationApiOutputConfig = {
}
/**
- * Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.
+ * 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'.
*/
-export type EvaluationApiTargetConfig = {
- /**
- * For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight.
- * @minimum 10
- * @maximum 7200
- */
- window_seconds?: number
-}
+export type EvaluationApiTargetConfig =
+ | {
+ /** Wait a fixed window after the first matching generation, then evaluate. */
+ 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.
+ * @minimum 10
+ * @maximum 7200
+ */
+ window_seconds?: number
+ }
+ | {
+ /** Evaluate once the trace has had no new activity for the quiet period. */
+ strategy: 'inactivity'
+ /**
+ * Seconds without new trace activity before the trace counts as settled.
+ * @minimum 10
+ * @maximum 1800
+ */
+ 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.
+ * @minimum 60
+ * @maximum 7200
+ */
+ max_age_seconds?: number
+ }
export interface EvaluationApi {
readonly id: string
@@ -579,12 +598,12 @@ 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.
+ /** 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.
*
* * `generation` - Generation
* * `trace` - Trace */
target?: EvaluationTargetEnumApi
- /** Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'. */
+ /** 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_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
@@ -636,16 +655,35 @@ export type PatchedEvaluationApiOutputConfig = {
}
/**
- * Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.
+ * 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'.
*/
-export type PatchedEvaluationApiTargetConfig = {
- /**
- * For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight.
- * @minimum 10
- * @maximum 7200
- */
- window_seconds?: number
-}
+export type PatchedEvaluationApiTargetConfig =
+ | {
+ /** Wait a fixed window after the first matching generation, then evaluate. */
+ 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.
+ * @minimum 10
+ * @maximum 7200
+ */
+ window_seconds?: number
+ }
+ | {
+ /** Evaluate once the trace has had no new activity for the quiet period. */
+ strategy: 'inactivity'
+ /**
+ * Seconds without new trace activity before the trace counts as settled.
+ * @minimum 10
+ * @maximum 1800
+ */
+ 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.
+ * @minimum 60
+ * @maximum 7200
+ */
+ max_age_seconds?: number
+ }
export interface PatchedEvaluationApi {
readonly id?: string
@@ -682,12 +720,12 @@ 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.
+ /** 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.
*
* * `generation` - Generation
* * `trace` - Trace */
target?: EvaluationTargetEnumApi
- /** Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'. */
+ /** 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_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
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index 495da05845ec..248b19f7a9aa 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -112,9 +112,18 @@ export const evaluationsCreateBodyConditionsItemRolloutPercentageDefault = 100
export const evaluationsCreateBodyConditionsItemRolloutPercentageMin = 0
export const evaluationsCreateBodyConditionsItemRolloutPercentageMax = 100
-export const evaluationsCreateBodyTargetConfigWindowSecondsDefault = 1800
-export const evaluationsCreateBodyTargetConfigWindowSecondsMin = 10
-export const evaluationsCreateBodyTargetConfigWindowSecondsMax = 7200
+export const evaluationsCreateBodyTargetConfigOneStrategyDefault = `fixed_window`
+export const evaluationsCreateBodyTargetConfigOneWindowSecondsDefault = 1800
+export const evaluationsCreateBodyTargetConfigOneWindowSecondsMin = 10
+export const evaluationsCreateBodyTargetConfigOneWindowSecondsMax = 7200
+
+export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsDefault = 300
+export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMin = 10
+export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMax = 1800
+
+export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsDefault = 7200
+export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMin = 60
+export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax = 7200
export const evaluationsCreateBodyModelConfigurationOneModelMax = 100
@@ -205,21 +214,48 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({
.describe('\* `generation` - Generation\n\* `trace` - Trace')
.optional()
.describe(
- "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n\* `generation` - Generation\n\* `trace` - Trace"
+ "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"
),
target_config: zod
- .object({
- window_seconds: zod
- .number()
- .min(evaluationsCreateBodyTargetConfigWindowSecondsMin)
- .max(evaluationsCreateBodyTargetConfigWindowSecondsMax)
- .default(evaluationsCreateBodyTargetConfigWindowSecondsDefault)
- .describe(
- "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight."
- ),
- })
+ .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)
+ .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.'
+ ),
+ }),
+ zod.object({
+ strategy: zod
+ .enum(['inactivity'])
+ .describe('Evaluate once the trace 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.'),
+ max_age_seconds: zod
+ .number()
+ .min(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMin)
+ .max(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax)
+ .default(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsDefault)
+ .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.'
+ ),
+ }),
+ ])
.optional()
- .describe("Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'."),
+ .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'."
+ ),
model_configuration: zod
.union([
zod
@@ -268,9 +304,18 @@ export const evaluationsUpdateBodyConditionsItemRolloutPercentageDefault = 100
export const evaluationsUpdateBodyConditionsItemRolloutPercentageMin = 0
export const evaluationsUpdateBodyConditionsItemRolloutPercentageMax = 100
-export const evaluationsUpdateBodyTargetConfigWindowSecondsDefault = 1800
-export const evaluationsUpdateBodyTargetConfigWindowSecondsMin = 10
-export const evaluationsUpdateBodyTargetConfigWindowSecondsMax = 7200
+export const evaluationsUpdateBodyTargetConfigOneStrategyDefault = `fixed_window`
+export const evaluationsUpdateBodyTargetConfigOneWindowSecondsDefault = 1800
+export const evaluationsUpdateBodyTargetConfigOneWindowSecondsMin = 10
+export const evaluationsUpdateBodyTargetConfigOneWindowSecondsMax = 7200
+
+export const evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsDefault = 300
+export const evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsMin = 10
+export const evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsMax = 1800
+
+export const evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsDefault = 7200
+export const evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMin = 60
+export const evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMax = 7200
export const evaluationsUpdateBodyModelConfigurationOneModelMax = 100
@@ -361,21 +406,48 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod.object({
.describe('\* `generation` - Generation\n\* `trace` - Trace')
.optional()
.describe(
- "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n\* `generation` - Generation\n\* `trace` - Trace"
+ "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"
),
target_config: zod
- .object({
- window_seconds: zod
- .number()
- .min(evaluationsUpdateBodyTargetConfigWindowSecondsMin)
- .max(evaluationsUpdateBodyTargetConfigWindowSecondsMax)
- .default(evaluationsUpdateBodyTargetConfigWindowSecondsDefault)
- .describe(
- "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight."
- ),
- })
+ .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)
+ .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.'
+ ),
+ }),
+ zod.object({
+ strategy: zod
+ .enum(['inactivity'])
+ .describe('Evaluate once the trace 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.'),
+ max_age_seconds: zod
+ .number()
+ .min(evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMin)
+ .max(evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMax)
+ .default(evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsDefault)
+ .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.'
+ ),
+ }),
+ ])
.optional()
- .describe("Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'."),
+ .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'."
+ ),
model_configuration: zod
.union([
zod
@@ -424,9 +496,18 @@ export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMin = 0
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMax = 100
-export const evaluationsPartialUpdateBodyTargetConfigWindowSecondsDefault = 1800
-export const evaluationsPartialUpdateBodyTargetConfigWindowSecondsMin = 10
-export const evaluationsPartialUpdateBodyTargetConfigWindowSecondsMax = 7200
+export const evaluationsPartialUpdateBodyTargetConfigOneStrategyDefault = `fixed_window`
+export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsDefault = 1800
+export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMin = 10
+export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMax = 7200
+
+export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsDefault = 300
+export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMin = 10
+export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMax = 1800
+
+export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsDefault = 7200
+export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMin = 60
+export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax = 7200
export const evaluationsPartialUpdateBodyModelConfigurationOneModelMax = 100
@@ -519,21 +600,48 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe('\* `generation` - Generation\n\* `trace` - Trace')
.optional()
.describe(
- "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n\* `generation` - Generation\n\* `trace` - Trace"
+ "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"
),
target_config: zod
- .object({
- window_seconds: zod
- .number()
- .min(evaluationsPartialUpdateBodyTargetConfigWindowSecondsMin)
- .max(evaluationsPartialUpdateBodyTargetConfigWindowSecondsMax)
- .default(evaluationsPartialUpdateBodyTargetConfigWindowSecondsDefault)
- .describe(
- "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight."
- ),
- })
+ .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)
+ .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.'
+ ),
+ }),
+ zod.object({
+ strategy: zod
+ .enum(['inactivity'])
+ .describe('Evaluate once the trace 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.'),
+ max_age_seconds: zod
+ .number()
+ .min(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMin)
+ .max(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax)
+ .default(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsDefault)
+ .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.'
+ ),
+ }),
+ ])
.optional()
- .describe("Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'."),
+ .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'."
+ ),
model_configuration: zod
.union([
zod
diff --git a/products/ai_observability/skills/creating-online-evaluations/SKILL.md b/products/ai_observability/skills/creating-online-evaluations/SKILL.md
index 39051303fc06..3bb48acf78b8 100644
--- a/products/ai_observability/skills/creating-online-evaluations/SKILL.md
+++ b/products/ai_observability/skills/creating-online-evaluations/SKILL.md
@@ -75,9 +75,18 @@ 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. |
-For a trace target, send `"target": "trace"` and
-`"target_config": { "window_seconds": 1800 }`. The wait must be between 10 seconds and 2 hours and defaults
-to 30 minutes. Conditions still match the generation that triggers the run; the evaluator itself receives
+For a trace target, send `"target": "trace"` plus a settle config that controls when the trace is
+evaluated, discriminated on `strategy`:
+
+- `{ "strategy": "fixed_window", "window_seconds": 1800 }` — evaluate a fixed wait after the first
+ matching generation. Between 10 seconds and 2 hours, defaults to 30 minutes. A `target_config`
+ without a `strategy` key means this.
+- `{ "strategy": "inactivity", "quiet_period_seconds": 300, "max_age_seconds": 7200 }` — evaluate once
+ the trace has had no new activity for the quiet period (10 seconds to 30 minutes,
+ 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).
+
+Conditions still match the generation that triggers the run; the evaluator itself receives
the complete trace. Sentiment evaluations support only the generation target.
New Hog source should use the globals shared by both targets:
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 d965ec052e95..ddfd2f2fefe0 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
@@ -15,7 +15,7 @@ schemas below are rendered from the backend Pydantic models at build time, so th
| `output_config` | no | `{ "allows_na": bool }` for boolean; `{}` for sentiment. |
| `model_configuration` | llm_judge only | Provider/model/key. Rejected on `hog`/`sentiment`. |
| `target` | no | `"generation"` (default) or `"trace"`. Sentiment supports only `"generation"`. |
-| `target_config` | trace only | `{ "window_seconds": 10..7200 }`; defaults to 1800 seconds for a trace target. |
+| `target_config` | trace only | Settle config discriminated on `strategy` (below); defaults to a 1800-second fixed window. |
| `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`. |
@@ -25,8 +25,12 @@ Valid `(evaluation_type, output_type)` pairs: `(hog, boolean)`, `(llm_judge, boo
## `target` and `target_config`
- `"target": "generation"` runs once for each matching generation and uses an empty `target_config`.
-- `"target": "trace"` runs once for the whole trace after the first matching generation. Set
- `target_config.window_seconds` to control how long PostHog waits for the trace to finish before evaluating it.
+- `"target": "trace"` runs once for the whole trace. `target_config` picks the settle strategy:
+ - `{ "strategy": "fixed_window", "window_seconds": 10..7200 }` waits a fixed delay after the first
+ matching generation (defaults to 1800). A config without a `strategy` key means this.
+ - `{ "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.
@@ -130,7 +134,16 @@ The same Hog source works for a whole trace. Change only the target fields:
```json
{
"target": "trace",
- "target_config": { "window_seconds": 1800 }
+ "target_config": { "strategy": "fixed_window", "window_seconds": 1800 }
+}
+```
+
+Or evaluate when the trace goes quiet instead of after a fixed delay:
+
+```json
+{
+ "target": "trace",
+ "target_config": { "strategy": "inactivity", "quiet_period_seconds": 300, "max_age_seconds": 7200 }
}
```
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7621a6ae8d3c..fb8a0758a8bd 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25022,15 +25022,32 @@ export namespace Schemas {
};
/**
- * Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.
+ * 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'.
*/
export type EvaluationTargetConfig = {
+ /** Wait a fixed window after the first matching generation, then evaluate. */
+ strategy?: 'fixed_window';
/**
- * For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight.
+ * 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.
* @minimum 10
* @maximum 7200
*/
window_seconds?: number;
+ } | {
+ /** Evaluate once the trace has had no new activity for the quiet period. */
+ strategy: 'inactivity';
+ /**
+ * Seconds without new trace activity before the trace counts as settled.
+ * @minimum 10
+ * @maximum 1800
+ */
+ 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.
+ * @minimum 60
+ * @maximum 7200
+ */
+ max_age_seconds?: number;
};
/**
@@ -25209,12 +25226,12 @@ 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.
+ /** 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.
*
* * `generation` - Generation
* * `trace` - Trace */
target?: EvaluationTargetEnum;
- /** Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'. */
+ /** 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_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;
@@ -48022,15 +48039,32 @@ export namespace Schemas {
};
/**
- * Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.
+ * 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'.
*/
export type PatchedEvaluationTargetConfig = {
+ /** Wait a fixed window after the first matching generation, then evaluate. */
+ strategy?: 'fixed_window';
/**
- * For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight.
+ * 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.
* @minimum 10
* @maximum 7200
*/
window_seconds?: number;
+ } | {
+ /** Evaluate once the trace has had no new activity for the quiet period. */
+ strategy: 'inactivity';
+ /**
+ * Seconds without new trace activity before the trace counts as settled.
+ * @minimum 10
+ * @maximum 1800
+ */
+ 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.
+ * @minimum 60
+ * @maximum 7200
+ */
+ max_age_seconds?: number;
};
export interface PatchedEvaluation {
@@ -48068,12 +48102,12 @@ 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.
+ /** 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.
*
* * `generation` - Generation
* * `trace` - Trace */
target?: EvaluationTargetEnum;
- /** Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'. */
+ /** 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_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;
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index ee680994d2f5..8289651baf44 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -139,9 +139,18 @@ export const evaluationsCreateBodyConditionsItemRolloutPercentageDefault = 100
export const evaluationsCreateBodyConditionsItemRolloutPercentageMin = 0
export const evaluationsCreateBodyConditionsItemRolloutPercentageMax = 100
-export const evaluationsCreateBodyTargetConfigWindowSecondsDefault = 1800
-export const evaluationsCreateBodyTargetConfigWindowSecondsMin = 10
-export const evaluationsCreateBodyTargetConfigWindowSecondsMax = 7200
+export const evaluationsCreateBodyTargetConfigOneStrategyDefault = `fixed_window`
+export const evaluationsCreateBodyTargetConfigOneWindowSecondsDefault = 1800
+export const evaluationsCreateBodyTargetConfigOneWindowSecondsMin = 10
+export const evaluationsCreateBodyTargetConfigOneWindowSecondsMax = 7200
+
+export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsDefault = 300
+export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMin = 10
+export const evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMax = 1800
+
+export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsDefault = 7200
+export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMin = 60
+export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax = 7200
export const evaluationsCreateBodyModelConfigurationOneModelMax = 100
@@ -232,21 +241,48 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({
.describe('\* `generation` - Generation\n\* `trace` - Trace')
.optional()
.describe(
- "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n\* `generation` - Generation\n\* `trace` - Trace"
+ "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"
),
target_config: zod
- .object({
- window_seconds: zod
- .number()
- .min(evaluationsCreateBodyTargetConfigWindowSecondsMin)
- .max(evaluationsCreateBodyTargetConfigWindowSecondsMax)
- .default(evaluationsCreateBodyTargetConfigWindowSecondsDefault)
- .describe(
- "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight."
- ),
- })
+ .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)
+ .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.'
+ ),
+ }),
+ zod.object({
+ strategy: zod
+ .enum(['inactivity'])
+ .describe('Evaluate once the trace 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.'),
+ max_age_seconds: zod
+ .number()
+ .min(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMin)
+ .max(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax)
+ .default(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsDefault)
+ .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.'
+ ),
+ }),
+ ])
.optional()
- .describe("Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'."),
+ .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'."
+ ),
model_configuration: zod
.union([
zod
@@ -313,9 +349,18 @@ export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMin = 0
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMax = 100
-export const evaluationsPartialUpdateBodyTargetConfigWindowSecondsDefault = 1800
-export const evaluationsPartialUpdateBodyTargetConfigWindowSecondsMin = 10
-export const evaluationsPartialUpdateBodyTargetConfigWindowSecondsMax = 7200
+export const evaluationsPartialUpdateBodyTargetConfigOneStrategyDefault = `fixed_window`
+export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsDefault = 1800
+export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMin = 10
+export const evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMax = 7200
+
+export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsDefault = 300
+export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMin = 10
+export const evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMax = 1800
+
+export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsDefault = 7200
+export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMin = 60
+export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax = 7200
export const evaluationsPartialUpdateBodyModelConfigurationOneModelMax = 100
@@ -408,21 +453,48 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe('\* `generation` - Generation\n\* `trace` - Trace')
.optional()
.describe(
- "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n\* `generation` - Generation\n\* `trace` - Trace"
+ "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"
),
target_config: zod
- .object({
- window_seconds: zod
- .number()
- .min(evaluationsPartialUpdateBodyTargetConfigWindowSecondsMin)
- .max(evaluationsPartialUpdateBodyTargetConfigWindowSecondsMax)
- .default(evaluationsPartialUpdateBodyTargetConfigWindowSecondsDefault)
- .describe(
- "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight."
- ),
- })
+ .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)
+ .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.'
+ ),
+ }),
+ zod.object({
+ strategy: zod
+ .enum(['inactivity'])
+ .describe('Evaluate once the trace 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.'),
+ max_age_seconds: zod
+ .number()
+ .min(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMin)
+ .max(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax)
+ .default(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsDefault)
+ .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.'
+ ),
+ }),
+ ])
.optional()
- .describe("Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'."),
+ .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'."
+ ),
model_configuration: zod
.union([
zod
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 3bc620de2e54..f5a14793a679 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,22 +167,57 @@
"type": "string"
},
"target": {
- "description": "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n* `generation` - Generation\n* `trace` - Trace",
+ "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"],
"type": "string"
},
"target_config": {
- "description": "Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.",
- "properties": {
- "window_seconds": {
- "default": 1800,
- "description": "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight.",
- "maximum": 7200,
- "minimum": 10,
- "type": "number"
+ "anyOf": [
+ {
+ "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,
+ "minimum": 10,
+ "type": "number"
+ }
+ },
+ "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,
+ "minimum": 60,
+ "type": "number"
+ },
+ "quiet_period_seconds": {
+ "default": 300,
+ "description": "Seconds without new trace activity before the trace counts as settled.",
+ "maximum": 1800,
+ "minimum": 10,
+ "type": "number"
+ },
+ "strategy": {
+ "description": "Evaluate once the trace has had no new activity for the quiet period.",
+ "enum": ["inactivity"],
+ "type": "string"
+ }
+ },
+ "required": ["strategy"],
+ "type": "object"
}
- },
- "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'."
}
},
"required": ["name", "evaluation_type", "output_type"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json
index 5d88eb3062cd..a6343ffdad93 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,22 +171,57 @@
"type": "string"
},
"target": {
- "description": "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once: the first matching generation schedules a run that waits for the trace to settle, then evaluates all of its events together. Condition filters still match individual generations — a trace is evaluated when any of its generations matches, and sampling applies per trace.\n\n* `generation` - Generation\n* `trace` - Trace",
+ "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"],
"type": "string"
},
"target_config": {
- "description": "Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'.",
- "properties": {
- "window_seconds": {
- "default": 1800,
- "description": "For 'trace' target: seconds to wait after the first matching generation before evaluating the whole trace. Captured when the run is scheduled — editing it does not change trace runs already in flight.",
- "maximum": 7200,
- "minimum": 10,
- "type": "number"
+ "anyOf": [
+ {
+ "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,
+ "minimum": 10,
+ "type": "number"
+ }
+ },
+ "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,
+ "minimum": 60,
+ "type": "number"
+ },
+ "quiet_period_seconds": {
+ "default": 300,
+ "description": "Seconds without new trace activity before the trace counts as settled.",
+ "maximum": 1800,
+ "minimum": 10,
+ "type": "number"
+ },
+ "strategy": {
+ "description": "Evaluate once the trace has had no new activity for the quiet period.",
+ "enum": ["inactivity"],
+ "type": "string"
+ }
+ },
+ "required": ["strategy"],
+ "type": "object"
}
- },
- "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'."
}
},
"required": ["id"],