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.

chore(llma): remove ai_events table migration scaffolding (#64322)

Carlos Marchalf5597bc55149
diff --git a/.agents/skills/generating-clickhouse-query-performance-reports/references/hogql-deep-dive.md b/.agents/skills/generating-clickhouse-query-performance-reports/references/hogql-deep-dive.md
index d4972e0ccbcc..0d8892777866 100644
--- a/.agents/skills/generating-clickhouse-query-performance-reports/references/hogql-deep-dive.md
+++ b/.agents/skills/generating-clickhouse-query-performance-reports/references/hogql-deep-dive.md
@@ -50,7 +50,7 @@ There is **no single boolean "written by AI" column.** Identify it from `lc_prod
Filter: `lc_product IN ('max_ai','mcp') OR lc_feature IN ('mcp','posthog_ai')`.
**Do not use `ai_query_source`.** Despite the name it records which AI-events table the LLM-analytics
-resolver chose (`dedicated_table` / `shared_table` / `shared_table_fallback`), not "AI authored this".
+resolver chose (`dedicated_table` / `shared_table_fallback`), not "AI authored this".
It is also not materialized as an `lc_*` column in the archive.
Caveats:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index ca93adfb19e8..4f70fbd125aa 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -243,7 +243,6 @@ export const FEATURE_FLAGS = {
AA_TEST_BAYESIAN_NEW: 'aa-test-bayesian-new', // owner: #team-experiments
ACTION_REFERENCE_COUNT: 'action-reference-count', // owner: @andyzzhao #team-product-analytics, gates bulk action reference counting on actions list
ADVANCE_MARKETING_ANALYTICS_SETTINGS: 'advance-marketing-analytics-settings', // owner: @jabahamondes #team-web-analytics
- AI_EVENTS_TABLE_ROLLOUT: 'ai-events-table-rollout', // owner: #team-ai-observability, gates reads off the dedicated ai_events table
AI_GATEWAY: 'ai-gateway', // owner: #team-ai-gateway, gates the AI gateway UI and llm_gateway:read on project secret API keys
/** Alert edit modal: check history chart + chart/table toggle (table remains when off). */
ALERTS_15_MINUTE_INTERVAL: 'alerts-15-minute-interval', // owner: #team-analytics-platform, gates 15-minute insight alert interval
diff --git a/nodejs/src/ai-observability/config.ts b/nodejs/src/ai-observability/config.ts
index cf86b119bf52..0d630c408734 100644
--- a/nodejs/src/ai-observability/config.ts
+++ b/nodejs/src/ai-observability/config.ts
@@ -9,18 +9,6 @@ export type AIObservabilityConfig = {
TEMPORAL_SECRET_KEY: string | undefined
TEMPORAL_FALLBACK_SECRET_KEYS: string
-
- // Topic the evaluation scheduler reads from. 'events' is the legacy shared
- // events topic; 'ai_events' is the AI-only topic which carries the
- // unstripped payload required for teams that have heavy props stripped from
- // the events topic. Two scheduler deployments run in parallel during the
- // rollout: one on each topic, partitioning teams between them via
- // LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS — the AI-events deployment processes
- // teams in that list, the events deployment processes everything else.
- // Must be a superset of the strip-heavy team list, otherwise evals and
- // taggers silently break for teams in the difference set (status quo bug).
- LLMA_EVAL_SCHEDULER_TOPIC: 'events' | 'ai_events'
- LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS: string
LLMA_EVAL_SCHEDULER_PROVIDER_KEY_GATING: boolean
}
@@ -34,8 +22,6 @@ export function getDefaultAIObservabilityConfig(): AIObservabilityConfig {
TEMPORAL_CLIENT_KEY: undefined,
TEMPORAL_SECRET_KEY: process.env.TEMPORAL_SECRET_KEY ?? process.env.SECRET_KEY,
TEMPORAL_FALLBACK_SECRET_KEYS: process.env.TEMPORAL_FALLBACK_SECRET_KEYS ?? '',
- LLMA_EVAL_SCHEDULER_TOPIC: 'events',
- LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS: '',
LLMA_EVAL_SCHEDULER_PROVIDER_KEY_GATING: false,
}
}
diff --git a/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts b/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts
index c110f06408da..5787c8d66871 100644
--- a/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts
+++ b/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts
@@ -6,8 +6,6 @@ import {
createEvaluationCondition,
createTagger,
} from '~/ai-observability/_tests/fixtures'
-import { getDefaultAIObservabilityConfig } from '~/ai-observability/config'
-import { parseTeamsList } from '~/utils/env-utils'
import { logger } from '~/utils/logger'
import {
@@ -17,7 +15,6 @@ import {
eachBatchEvaluationScheduler,
filterAndParseMessages,
groupEventsByTeam,
- teamShouldBeProcessed,
unwrapOrLog,
} from './evaluation-scheduler'
@@ -442,45 +439,7 @@ describe('Evaluation Scheduler', () => {
})
})
- describe('teamShouldBeProcessed', () => {
- // Drives the partition between the two scheduler deployments. Both must read
- // the same aiTopicTeams value or you get gap (some team handled by neither)
- // or overlap (some team handled by both → broken results may cement).
- const cases: Array<{
- name: string
- topic: 'events' | 'ai_events'
- teams: number[] | '*'
- teamId: number
- expected: boolean
- }> = [
- { name: 'ai_events keeps team in list', topic: 'ai_events', teams: [2, 99], teamId: 2, expected: true },
- {
- name: 'ai_events drops team not in list',
- topic: 'ai_events',
- teams: [2, 99],
- teamId: 7,
- expected: false,
- },
- { name: 'events drops team in list', topic: 'events', teams: [2, 99], teamId: 2, expected: false },
- { name: 'events keeps team not in list', topic: 'events', teams: [2, 99], teamId: 7, expected: true },
- { name: 'ai_events keeps everything when *', topic: 'ai_events', teams: '*', teamId: 1234, expected: true },
- { name: 'events drops everything when *', topic: 'events', teams: '*', teamId: 1234, expected: false },
- {
- name: 'ai_events drops everything when empty list',
- topic: 'ai_events',
- teams: [],
- teamId: 2,
- expected: false,
- },
- { name: 'events keeps everything when empty list', topic: 'events', teams: [], teamId: 2, expected: true },
- ]
-
- it.each(cases)('$name', ({ topic, teams, teamId, expected }) => {
- expect(teamShouldBeProcessed(teamId, topic, teams)).toBe(expected)
- })
- })
-
- describe('eachBatchEvaluationScheduler partitioning', () => {
+ describe('eachBatchEvaluationScheduler batching', () => {
const noopEvaluationManager = {
getEvaluationsForTeams: jest.fn().mockResolvedValue({}),
} as unknown as import('~/ai-observability/services/evaluation-manager.service').EvaluationManagerService
@@ -500,90 +459,25 @@ describe('Evaluation Scheduler', () => {
value: Buffer.from(JSON.stringify(createAiGenerationEvent(teamIdForEvent))),
}) as any
- it('ai_events deployment only fetches definitions for teams in the list', async () => {
- await eachBatchEvaluationScheduler(
- [messageFor(2), messageFor(7), messageFor(99)],
- noopEvaluationManager,
- noopTaggerManager,
- noopTemporal,
- { topic: 'ai_events', aiTopicTeams: [2, 99] }
- )
-
- expect(noopEvaluationManager.getEvaluationsForTeams).toHaveBeenCalledTimes(1)
- const teamsAsked = (noopEvaluationManager.getEvaluationsForTeams as jest.Mock).mock.calls[0][0] as number[]
- expect(teamsAsked.sort()).toEqual([2, 99])
- })
-
- it('events deployment only fetches definitions for teams NOT in the list', async () => {
+ it('fetches definitions for every team in the batch', async () => {
await eachBatchEvaluationScheduler(
[messageFor(2), messageFor(7), messageFor(99)],
noopEvaluationManager,
noopTaggerManager,
- noopTemporal,
- { topic: 'events', aiTopicTeams: [2, 99] }
+ noopTemporal
)
expect(noopEvaluationManager.getEvaluationsForTeams).toHaveBeenCalledTimes(1)
const teamsAsked = (noopEvaluationManager.getEvaluationsForTeams as jest.Mock).mock.calls[0][0] as number[]
- expect(teamsAsked).toEqual([7])
+ expect(teamsAsked.sort((a, b) => a - b)).toEqual([2, 7, 99])
})
- it('skips Postgres entirely when partition drops every event', async () => {
- await eachBatchEvaluationScheduler(
- [messageFor(7), messageFor(8)],
- noopEvaluationManager,
- noopTaggerManager,
- noopTemporal,
- { topic: 'ai_events', aiTopicTeams: [2, 99] }
- )
+ it('skips Postgres entirely when the batch has no $ai_generation events', async () => {
+ await eachBatchEvaluationScheduler([], noopEvaluationManager, noopTaggerManager, noopTemporal)
expect(noopEvaluationManager.getEvaluationsForTeams).not.toHaveBeenCalled()
expect(noopTaggerManager.getTaggersForTeams).not.toHaveBeenCalled()
})
-
- // Locks down the contract that gates the deploy ordering: a deployment
- // running the new image with neither LLMA_EVAL_SCHEDULER_TOPIC nor
- // LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS set in env behaves identically to
- // the legacy events-only consumer. This is what lets us land the new
- // image into state.yaml before any chart override is applied without
- // any risk of accidental traffic divergence.
- describe('default config preserves legacy behavior', () => {
- it('exposes "events" topic and empty team list as defaults', () => {
- const defaults = getDefaultAIObservabilityConfig()
- expect(defaults.LLMA_EVAL_SCHEDULER_TOPIC).toBe('events')
- expect(defaults.LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS).toBe('')
- })
-
- it('parsed defaults yield empty team list (not "*"), so events-mode processes everyone', () => {
- const defaults = getDefaultAIObservabilityConfig()
- const parsed = parseTeamsList(defaults.LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS)
- expect(parsed).toEqual([])
- expect(teamShouldBeProcessed(2, defaults.LLMA_EVAL_SCHEDULER_TOPIC, parsed)).toBe(true)
- expect(teamShouldBeProcessed(385921, defaults.LLMA_EVAL_SCHEDULER_TOPIC, parsed)).toBe(true)
- expect(teamShouldBeProcessed(7, defaults.LLMA_EVAL_SCHEDULER_TOPIC, parsed)).toBe(true)
- })
-
- it('eachBatchEvaluationScheduler with parsed defaults processes every team in the batch', async () => {
- const defaults = getDefaultAIObservabilityConfig()
- const partition = {
- topic: defaults.LLMA_EVAL_SCHEDULER_TOPIC,
- aiTopicTeams: parseTeamsList(defaults.LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS),
- }
-
- await eachBatchEvaluationScheduler(
- [messageFor(2), messageFor(7), messageFor(385921), messageFor(99)],
- noopEvaluationManager,
- noopTaggerManager,
- noopTemporal,
- partition
- )
-
- expect(noopEvaluationManager.getEvaluationsForTeams).toHaveBeenCalledTimes(1)
- const teamsAsked = (noopEvaluationManager.getEvaluationsForTeams as jest.Mock).mock
- .calls[0][0] as number[]
- expect(teamsAsked.sort((a, b) => a - b)).toEqual([2, 7, 99, 385921])
- })
- })
})
describe('eachBatchEvaluationScheduler provider key gate', () => {
@@ -629,14 +523,10 @@ describe('Evaluation Scheduler', () => {
})
;(evaluationManager.getEvaluationsForTeams as jest.Mock).mockResolvedValue({ [teamId]: [evaluation] })
- await eachBatchEvaluationScheduler(
- [messageFor(event)],
- evaluationManager,
- taggerManager,
- temporalService,
- { topic: 'events', aiTopicTeams: [] },
- { enabled: true, providerKeyManager }
- )
+ await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService, {
+ enabled: true,
+ providerKeyManager,
+ })
expect(providerKeyManager.getProviderKey).toHaveBeenCalledWith('key-1')
expect(temporalService.startEvaluationRunWorkflow).not.toHaveBeenCalled()
@@ -653,14 +543,10 @@ describe('Evaluation Scheduler', () => {
})
;(evaluationManager.getEvaluationsForTeams as jest.Mock).mockResolvedValue({ [teamId]: [evaluation] })
- await eachBatchEvaluationScheduler(
- [messageFor(event)],
- evaluationManager,
- taggerManager,
- temporalService,
- { topic: 'events', aiTopicTeams: [] },
- { enabled: true, providerKeyManager }
- )
+ await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService, {
+ enabled: true,
+ providerKeyManager,
+ })
expect(providerKeyManager.getProviderKey).not.toHaveBeenCalled()
expect(temporalService.startEvaluationRunWorkflow).toHaveBeenCalledWith(
@@ -685,14 +571,10 @@ describe('Evaluation Scheduler', () => {
})
;(evaluationManager.getEvaluationsForTeams as jest.Mock).mockResolvedValue({ [teamId]: [evaluation] })
- await eachBatchEvaluationScheduler(
- [messageFor(event)],
- evaluationManager,
- taggerManager,
- temporalService,
- { topic: 'events', aiTopicTeams: [] },
- { enabled: true, providerKeyManager }
- )
+ await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService, {
+ enabled: true,
+ providerKeyManager,
+ })
expect(providerKeyManager.getProviderKey).not.toHaveBeenCalled()
expect(temporalService.startEvaluationRunWorkflow).toHaveBeenCalledWith(
@@ -713,14 +595,10 @@ describe('Evaluation Scheduler', () => {
})
;(taggerManager.getTaggersForTeams as jest.Mock).mockResolvedValue({ [teamId]: [tagger] })
- await eachBatchEvaluationScheduler(
- [messageFor(event)],
- evaluationManager,
- taggerManager,
- temporalService,
- { topic: 'events', aiTopicTeams: [] },
- { enabled: true, providerKeyManager }
- )
+ await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService, {
+ enabled: true,
+ providerKeyManager,
+ })
expect(providerKeyManager.getProviderKey).toHaveBeenCalledWith('key-1')
expect(temporalService.startTaggerRunWorkflow).not.toHaveBeenCalled()
@@ -738,14 +616,10 @@ describe('Evaluation Scheduler', () => {
;(evaluationManager.getEvaluationsForTeams as jest.Mock).mockResolvedValue({ [teamId]: [evaluation] })
;(providerKeyManager.getProviderKey as jest.Mock).mockRejectedValue(new Error('db down'))
- await eachBatchEvaluationScheduler(
- [messageFor(event)],
- evaluationManager,
- taggerManager,
- temporalService,
- { topic: 'events', aiTopicTeams: [] },
- { enabled: true, providerKeyManager }
- )
+ await eachBatchEvaluationScheduler([messageFor(event)], evaluationManager, taggerManager, temporalService, {
+ enabled: true,
+ providerKeyManager,
+ })
expect(temporalService.startEvaluationRunWorkflow).toHaveBeenCalledWith(
evaluation.id,
diff --git a/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts b/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
index b1e0724d0ff4..1d40dccfc3fc 100644
--- a/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
+++ b/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
@@ -1,24 +1,13 @@
/**
* Evaluation Scheduler
*
- * Consumes AI events (e.g., $ai_generation) from a Kafka topic, matches them
- * against evaluation filters, and triggers evaluation workflows via Temporal
- * when conditions are met.
+ * Consumes AI events (e.g., $ai_generation) from the ai_events Kafka topic
+ * (clickhouse_ai_events_json), matches them against evaluation filters, and
+ * triggers evaluation workflows via Temporal when conditions are met.
*
- * Two deployments run in parallel during the AI events table rollout, each
- * reading a different topic and partitioning teams between them via
- * LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS:
- *
- * - topic=events → reads clickhouse_events_json, processes teams NOT in the list.
- * - topic=ai_events → reads clickhouse_ai_events_json, processes teams IN the list.
- *
- * The events topic strips heavy AI properties for teams in the strip-heavy
- * rollout, which would leave the judge grading empty input/output. Routing
- * those teams to the ai_events topic gets the unstripped payload.
- *
- * The two deployments cannot double-fire: the same (evaluation_id, event_uuid)
- * yields the same Temporal workflow ID with USE_EXISTING — but the per-team
- * partition makes that a backstop, not the primary correctness mechanism.
+ * The ai_events topic carries the unstripped event payload (the events topic
+ * has the heavy AI properties stripped), so the judge always sees the full
+ * input/output it needs to grade.
*/
import * as crypto from 'crypto'
import { Message } from 'node-rdkafka'
@@ -35,20 +24,16 @@ import {
} from '../ai-observability/services/temporal.service'
import { Evaluation, EvaluationConditionSet, Matchable, Tagger } from '../ai-observability/types'
import { execHog } from '../cdp/utils/hog-exec'
-import { KAFKA_CLICKHOUSE_AI_EVENTS_JSON, KAFKA_EVENTS_JSON, prefix as KAFKA_PREFIX } from '../config/kafka-topics'
+import { KAFKA_CLICKHOUSE_AI_EVENTS_JSON, prefix as KAFKA_PREFIX } from '../config/kafka-topics'
import { createKafkaConsumer } from '../kafka/consumer'
import { PluginServerService, RawKafkaEvent } from '../types'
import { PostgresRouter } from '../utils/db/postgres'
-import { parseTeamsList } from '../utils/env-utils'
import { parseJSON } from '../utils/json-parse'
import { logger } from '../utils/logger'
import { PubSub } from '../utils/pubsub'
export type EvaluationSchedulerConfig = TemporalServiceConfig &
- Pick<
- AIObservabilityConfig,
- 'LLMA_EVAL_SCHEDULER_TOPIC' | 'LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS' | 'LLMA_EVAL_SCHEDULER_PROVIDER_KEY_GATING'
- >
+ Pick<AIObservabilityConfig, 'LLMA_EVAL_SCHEDULER_PROVIDER_KEY_GATING'>
export interface EvaluationSchedulerDeps {
postgres: PostgresRouter
@@ -84,12 +69,6 @@ const evaluationSchedulerHeaderValues = new Counter({
labelNames: ['header_value'],
})
-const evaluationSchedulerTeamPartition = new Counter({
- name: 'evaluation_scheduler_team_partition',
- help: 'Events kept vs dropped by the team partition filter',
- labelNames: ['outcome'], // kept | dropped
-})
-
// Pure functions for testability
/**
@@ -110,29 +89,6 @@ export function unwrapOrLog<T extends Record<string, unknown>>(
return {} as T
}
-/**
- * Returns true if the given team should be processed by this deployment. Mode
- * is implicit from the topic: ai_events processes teams in the list, events
- * processes teams not in the list. The two deployments must read the same
- * `aiTopicTeams` value or you get either gap (some team handled by neither) or
- * overlap (some team handled by both → broken results may cement via Temporal
- * USE_EXISTING dedup before correct ones arrive). '*' is the final-state
- * migration: every team has moved to ai_events and the events deployment
- * becomes a no-op.
- */
-export function teamShouldBeProcessed(
- teamId: number,
- topic: 'events' | 'ai_events',
- aiTopicTeams: number[] | '*'
-): boolean {
- const isAiTopicConsumer = topic === 'ai_events'
- if (aiTopicTeams === '*') {
- return isAiTopicConsumer
- }
- const inList = aiTopicTeams.includes(teamId)
- return isAiTopicConsumer ? inList : !inList
-}
-
export function filterAndParseMessages(messages: Message[]): RawKafkaEvent[] {
return messages
.filter((message) => {
@@ -283,23 +239,12 @@ export const startEvaluationScheduler = async (
config: EvaluationSchedulerConfig,
deps: EvaluationSchedulerDeps
): Promise<PluginServerService> => {
- const topic = config.LLMA_EVAL_SCHEDULER_TOPIC
- if (topic !== 'events' && topic !== 'ai_events') {
- throw new Error(`Invalid LLMA_EVAL_SCHEDULER_TOPIC: ${topic as string}. Must be 'events' or 'ai_events'.`)
- }
- const aiTopicTeams = parseTeamsList(config.LLMA_EVAL_SCHEDULER_AI_TOPIC_TEAMS)
- // Distinct group id per topic so the two deployments never share offsets.
- // The events-topic group id is unchanged (no suffix) so the existing
- // production consumer keeps its committed offsets across this deploy.
- const groupId =
- topic === 'ai_events' ? `${KAFKA_PREFIX}evaluation-scheduler-ai-events` : `${KAFKA_PREFIX}evaluation-scheduler`
- const kafkaTopic = topic === 'ai_events' ? KAFKA_CLICKHOUSE_AI_EVENTS_JSON : KAFKA_EVENTS_JSON
+ const groupId = `${KAFKA_PREFIX}evaluation-scheduler-ai-events`
+ const kafkaTopic = KAFKA_CLICKHOUSE_AI_EVENTS_JSON
logger.info('🤖', 'Starting evaluation scheduler', {
- topic,
groupId,
kafkaTopic,
- aiTopicTeams: aiTopicTeams === '*' ? '*' : aiTopicTeams.join(','),
providerKeyGating: config.LLMA_EVAL_SCHEDULER_PROVIDER_KEY_GATING,
})
@@ -316,20 +261,10 @@ export const startEvaluationScheduler = async (
})
await kafkaConsumer.connect((messages) =>
- eachBatchEvaluationScheduler(
- messages,
- evaluationManager,
- taggerManager,
- temporalService,
- {
- topic,
- aiTopicTeams,
- },
- {
- enabled: config.LLMA_EVAL_SCHEDULER_PROVIDER_KEY_GATING,
- providerKeyManager,
- }
- )
+ eachBatchEvaluationScheduler(messages, evaluationManager, taggerManager, temporalService, {
+ enabled: config.LLMA_EVAL_SCHEDULER_PROVIDER_KEY_GATING,
+ providerKeyManager,
+ })
)
const onShutdown = async (): Promise<void> => {
@@ -344,11 +279,6 @@ export const startEvaluationScheduler = async (
}
}
-export interface EachBatchPartitionConfig {
- topic: 'events' | 'ai_events'
- aiTopicTeams: number[] | '*'
-}
-
export interface ProviderKeyGateOptions {
enabled: boolean
providerKeyManager?: Pick<ProviderKeyManagerService, 'getProviderKey'>
@@ -374,7 +304,6 @@ export async function eachBatchEvaluationScheduler(
evaluationManager: EvaluationManagerService,
taggerManager: TaggerManagerService,
temporalService: TemporalService,
- partition: EachBatchPartitionConfig,
providerKeyGate?: ProviderKeyGateOptions
): Promise<void> {
logger.debug('Processing batch', { messageCount: messages.length })
@@ -386,28 +315,19 @@ export async function eachBatchEvaluationScheduler(
evaluationSchedulerEventsFiltered.labels({ passed: 'false' }).inc(messages.length - aiGenerationEvents.length)
evaluationSchedulerEventsFiltered.labels({ passed: 'true' }).inc(aiGenerationEvents.length)
- // Apply the team partition before any Postgres lookups. Counterpart deployment
- // (other topic) is responsible for everything we drop here.
- const partitionedEvents = aiGenerationEvents.filter((event) => {
- const keep = teamShouldBeProcessed(event.team_id, partition.topic, partition.aiTopicTeams)
- evaluationSchedulerTeamPartition.labels({ outcome: keep ? 'kept' : 'dropped' }).inc()
- return keep
- })
-
logger.debug('Filtered batch', {
totalMessages: messages.length,
aiEventsFound: aiGenerationEvents.length,
- afterTeamPartition: partitionedEvents.length,
filteredOut: messages.length - aiGenerationEvents.length,
})
- if (partitionedEvents.length === 0) {
+ if (aiGenerationEvents.length === 0) {
return
}
- logger.debug('Found $ai_generation events', { count: partitionedEvents.length })
+ logger.debug('Found $ai_generation events', { count: aiGenerationEvents.length })
- const eventsByTeam = groupEventsByTeam(partitionedEvents)
+ const eventsByTeam = groupEventsByTeam(aiGenerationEvents)
const teamIds = Array.from(eventsByTeam.keys())
// Fetch evaluations and taggers independently — a transient DB failure on one
diff --git a/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap b/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap
index c2d5b52aabcd..6c548678226d 100644
--- a/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap
+++ b/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap
@@ -417,6 +417,29 @@ exports[`IngestionConsumer typical event processing ai event 1`] = `
"uuid": "<REPLACED-UUID-1>",
},
},
+ {
+ "headers": {
+ "productTrack": "llma",
+ },
+ "key": "<REPLACED-UUID-1>",
+ "topic": "clickhouse_ai_events_json_test",
+ "value": {
+ "captured_at": "2025-01-01 00:00:00.000",
+ "created_at": "2025-01-01 00:00:00.000",
+ "distinct_id": "user-1",
+ "elements_chain": "",
+ "event": "$ai_generation",
+ "person_created_at": "2025-01-01 00:00:00",
+ "person_id": "<REPLACED-UUID-0>",
+ "person_mode": "full",
+ "person_properties": "{"$current_url":"http://localhost:8000","$creator_event_uuid":"<REPLACED-UUID-1>","$initial_current_url":"http://localhost:8000"}",
+ "project_id": 2,
+ "properties": "{"$current_url":"http://localhost:8000","$ai_model":"gpt-4","$ai_provider":"openai","$ai_input_tokens":100,"$ai_output_tokens":50,"$ip":"127.0.0.1","$set":{"$current_url":"http://localhost:8000"},"$set_once":{"$initial_current_url":"http://localhost:8000"},"$ai_cache_reporting_exclusive":false,"$ai_input_cost_usd":0.003,"$ai_output_cost_usd":0.003,"$ai_request_cost_usd":0,"$ai_web_search_cost_usd":0,"$ai_total_cost_usd":0.006,"$ai_model_cost_used":"openai/gpt-4","$ai_cost_model_source":"openrouter","$ai_cost_model_provider":"openai"}",
+ "team_id": 2,
+ "timestamp": "2025-01-01 00:00:00.000",
+ "uuid": "<REPLACED-UUID-1>",
+ },
+ },
{
"headers": undefined,
"key": null,
diff --git a/nodejs/src/ingestion/common/ai-subpipeline.contract.ts b/nodejs/src/ingestion/common/ai-subpipeline.contract.ts
index 054778d6ef2f..2e04c4d0ecef 100644
--- a/nodejs/src/ingestion/common/ai-subpipeline.contract.ts
+++ b/nodejs/src/ingestion/common/ai-subpipeline.contract.ts
@@ -16,7 +16,6 @@ import { GroupStoreForBatch } from '~/ingestion/common/groups/group-store-for-ba
import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
import { EmitEventStepOutput } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { EventPipelineRunnerOptions } from '~/ingestion/common/steps/event-processing/event-pipeline-options'
-import { SplitAiEventsStepConfig } from '~/ingestion/common/steps/event-processing/split-ai-events-step'
import { PipelineBuilder, StartPipelineBuilder } from '~/ingestion/framework/builders/pipeline-builders'
import { TopHogWrapper } from '~/ingestion/framework/extensions/tophog'
import { PluginEvent } from '~/plugin-scaffold'
@@ -45,7 +44,6 @@ export interface AiEventSubpipelineConfig {
teamManager: TeamManager
groupTypeManager: GroupTypeManager
hogTransformer: HogTransformer
- splitAiEventsConfig: SplitAiEventsStepConfig
topHog: TopHogWrapper
}
diff --git a/nodejs/src/ingestion/common/steps/event-processing/split-ai-events-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/split-ai-events-step.test.ts
index 8e95c5ad3b9a..14b588baeaa3 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/split-ai-events-step.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/split-ai-events-step.test.ts
@@ -2,7 +2,7 @@ import { AI_EVENTS_OUTPUT, EVENTS_OUTPUT } from '~/common/outputs'
import { isOkResult } from '~/ingestion/framework/results'
import { ISOTimestamp, ProcessedEvent, ProjectId } from '~/types'
-import { SplitAiEventsStepConfig, createSplitAiEventsStep, parseSplitAiEventsConfig } from './split-ai-events-step'
+import { createSplitAiEventsStep } from './split-ai-events-step'
function createProcessedEvent(
properties: Record<string, unknown> = {},
@@ -27,163 +27,43 @@ function createProcessedEvent(
}
}
-const ENABLED_FOR_ALL: SplitAiEventsStepConfig = {
- enabled: true,
- enabledTeams: '*',
- enabledPercentage: 0,
- stripHeavyTeams: '*',
-}
-const ENABLED_NO_STRIP: SplitAiEventsStepConfig = {
- enabled: true,
- enabledTeams: '*',
- enabledPercentage: 0,
- stripHeavyTeams: [],
-}
-
describe('split-ai-events-step', () => {
- describe('parseSplitAiEventsConfig', () => {
- it.each([
- {
- enabled: true,
- teams: '*',
- stripTeams: '',
- expected: { enabled: true, enabledTeams: '*', enabledPercentage: 0, stripHeavyTeams: [] },
- },
- {
- enabled: false,
- teams: '*',
- stripTeams: '',
- expected: { enabled: false, enabledTeams: '*', enabledPercentage: 0, stripHeavyTeams: [] },
- },
- {
- enabled: true,
- teams: '1,2,3',
- stripTeams: '*',
- expected: { enabled: true, enabledTeams: [1, 2, 3], enabledPercentage: 0, stripHeavyTeams: '*' },
- },
- {
- enabled: true,
- teams: ' 1 , 2 ',
- stripTeams: '2',
- expected: { enabled: true, enabledTeams: [1, 2], enabledPercentage: 0, stripHeavyTeams: [2] },
- },
- {
- enabled: true,
- teams: '',
- stripTeams: '',
- expected: { enabled: true, enabledTeams: [], enabledPercentage: 0, stripHeavyTeams: [] },
- },
- {
- enabled: true,
- teams: 'abc,1',
- stripTeams: 'abc,2',
- expected: { enabled: true, enabledTeams: [1], enabledPercentage: 0, stripHeavyTeams: [2] },
- },
- ])(
- 'should parse enabled=$enabled teams=$teams stripTeams=$stripTeams',
- ({ enabled, teams, stripTeams, expected }) => {
- expect(parseSplitAiEventsConfig(enabled, teams, stripTeams)).toEqual(expected)
- }
- )
-
- it.each([
- { input: 25, expected: 25 },
- { input: 0, expected: 0 },
- { input: 100, expected: 100 },
- { input: 150, expected: 100 },
- { input: -5, expected: 0 },
- { input: NaN, expected: 0 },
- { input: Infinity, expected: 100 },
- ])('should clamp percentage $input -> $expected', ({ input, expected }) => {
- expect(parseSplitAiEventsConfig(true, '', '', input).enabledPercentage).toBe(expected)
- })
- })
-
- describe('feature flag behavior', () => {
- it('should pass through unchanged when disabled', async () => {
- const step = createSplitAiEventsStep({
- enabled: false,
- enabledTeams: '*',
- enabledPercentage: 0,
- stripHeavyTeams: '*',
- })
- const event = createProcessedEvent({ $ai_input: 'large input', $ai_model: 'gpt-4' })
-
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
+ const step = createSplitAiEventsStep()
- expect(result.value.eventsToEmit).toHaveLength(1)
- expect(result.value.eventsToEmit[0].event.properties).toHaveProperty('$ai_input')
+ it('should split an event with large AI properties into stripped + full', async () => {
+ const event = createProcessedEvent({
+ $ai_input: 'large input',
+ $ai_output: 'large output',
+ $ai_model: 'gpt-4',
+ $browser: 'Chrome',
})
- it('should pass through unchanged when team is not in the enabled list', async () => {
- const step = createSplitAiEventsStep({
- enabled: true,
- enabledTeams: [99, 100],
- enabledPercentage: 0,
- stripHeavyTeams: '*',
- })
- const event = createProcessedEvent({ $ai_input: 'large input' })
-
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
-
- expect(result.value.eventsToEmit).toHaveLength(1)
- })
-
- it('should split when team is in the enabled list', async () => {
- const step = createSplitAiEventsStep({
- enabled: true,
- enabledTeams: [1, 2],
- enabledPercentage: 0,
- stripHeavyTeams: '*',
- })
- const event = createProcessedEvent({ $ai_input: 'large input', $ai_model: 'gpt-4' })
-
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
-
- expect(result.value.eventsToEmit).toHaveLength(2)
- })
+ const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
+ expect(isOkResult(result)).toBe(true)
+ if (!isOkResult(result)) {
+ return
+ }
- it('should split when enabled for all teams', async () => {
- const step = createSplitAiEventsStep({
- enabled: true,
- enabledTeams: '*',
- enabledPercentage: 0,
- stripHeavyTeams: '*',
- })
- const event = createProcessedEvent({ $ai_input: 'large input', $ai_model: 'gpt-4' })
+ const { eventsToEmit } = result.value
+ expect(eventsToEmit).toHaveLength(2)
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 999 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
+ const [mainEntry, aiEntry] = eventsToEmit
+ expect(mainEntry.output).toBe(EVENTS_OUTPUT)
+ expect(aiEntry.output).toBe(AI_EVENTS_OUTPUT)
- expect(result.value.eventsToEmit).toHaveLength(2)
+ expect(mainEntry.event.properties).toEqual({ $ai_model: 'gpt-4', $browser: 'Chrome' })
+ expect(aiEntry.event.properties).toEqual({
+ $ai_input: 'large input',
+ $ai_output: 'large output',
+ $ai_model: 'gpt-4',
+ $browser: 'Chrome',
})
})
- describe('splitting behavior', () => {
- const step = createSplitAiEventsStep(ENABLED_FOR_ALL)
-
- it('should split an event with large AI properties into stripped + full', async () => {
- const event = createProcessedEvent({
- $ai_input: 'large input',
- $ai_output: 'large output',
- $ai_model: 'gpt-4',
- $browser: 'Chrome',
- })
+ it.each(['$ai_input', '$ai_output', '$ai_output_choices', '$ai_input_state', '$ai_output_state', '$ai_tools'])(
+ 'should strip %s from the main output event',
+ async (property) => {
+ const event = createProcessedEvent({ [property]: 'large value', $ai_model: 'gpt-4' })
const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
expect(isOkResult(result)).toBe(true)
@@ -194,40 +74,32 @@ describe('split-ai-events-step', () => {
const { eventsToEmit } = result.value
expect(eventsToEmit).toHaveLength(2)
- const [mainEntry, aiEntry] = eventsToEmit
- expect(mainEntry.output).toBe(EVENTS_OUTPUT)
- expect(aiEntry.output).toBe(AI_EVENTS_OUTPUT)
-
- expect(mainEntry.event.properties).toEqual({ $ai_model: 'gpt-4', $browser: 'Chrome' })
- expect(aiEntry.event.properties).toEqual({
- $ai_input: 'large input',
- $ai_output: 'large output',
- $ai_model: 'gpt-4',
- $browser: 'Chrome',
- })
- })
-
- it.each(['$ai_input', '$ai_output', '$ai_output_choices', '$ai_input_state', '$ai_output_state', '$ai_tools'])(
- 'should strip %s from the main output event',
- async (property) => {
- const event = createProcessedEvent({ [property]: 'large value', $ai_model: 'gpt-4' })
+ expect(eventsToEmit[0].event.properties).not.toHaveProperty(property)
+ expect(eventsToEmit[1].event.properties).toHaveProperty(property, 'large value')
+ }
+ )
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
+ it('should send AI event without large properties to both outputs', async () => {
+ const event = createProcessedEvent({ $ai_model: 'gpt-4', $browser: 'Chrome' }, { event: '$ai_metric' })
- const { eventsToEmit } = result.value
- expect(eventsToEmit).toHaveLength(2)
+ const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
+ expect(isOkResult(result)).toBe(true)
+ if (!isOkResult(result)) {
+ return
+ }
- expect(eventsToEmit[0].event.properties).not.toHaveProperty(property)
- expect(eventsToEmit[1].event.properties).toHaveProperty(property, 'large value')
- }
- )
+ const { eventsToEmit } = result.value
+ expect(eventsToEmit).toHaveLength(2)
+ expect(eventsToEmit[0].event).toBe(event)
+ expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
+ expect(eventsToEmit[1].event).toBe(event)
+ expect(eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
+ })
- it('should send AI event without large properties to both outputs', async () => {
- const event = createProcessedEvent({ $ai_model: 'gpt-4', $browser: 'Chrome' }, { event: '$ai_metric' })
+ it.each(['$ai_feedback', '$ai_evaluation', '$ai_generation', '$ai_span', '$ai_trace', '$ai_embedding'])(
+ 'should send %s without large properties to both outputs',
+ async (eventName) => {
+ const event = createProcessedEvent({ $ai_model: 'gpt-4' }, { event: eventName })
const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
expect(isOkResult(result)).toBe(true)
@@ -237,396 +109,127 @@ describe('split-ai-events-step', () => {
const { eventsToEmit } = result.value
expect(eventsToEmit).toHaveLength(2)
- expect(eventsToEmit[0].event).toBe(event)
expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
- expect(eventsToEmit[1].event).toBe(event)
expect(eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
- })
-
- it.each(['$ai_feedback', '$ai_evaluation', '$ai_generation', '$ai_span', '$ai_trace', '$ai_embedding'])(
- 'should send %s without large properties to both outputs',
- async (eventName) => {
- const event = createProcessedEvent({ $ai_model: 'gpt-4' }, { event: eventName })
-
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
-
- const { eventsToEmit } = result.value
- expect(eventsToEmit).toHaveLength(2)
- expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
- expect(eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
- }
- )
-
- it.each([
- { props: { $browser: 'Chrome' }, desc: 'without large AI properties' },
- { props: { $browser: 'Chrome', $ai_input: 'large input' }, desc: 'with large AI properties' },
- ])('should pass through non-AI event $desc to single output', async ({ props }) => {
- const event = createProcessedEvent(props, { event: '$pageview' })
-
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
-
- const { eventsToEmit } = result.value
- expect(eventsToEmit).toHaveLength(1)
- expect(eventsToEmit[0].event).toBe(event)
- expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
- })
-
- it('should handle multiple events independently', async () => {
- const aiEvent = createProcessedEvent({ $ai_input: 'large', $ai_model: 'gpt-4' }, { uuid: 'ai-1' })
- const regularEvent = createProcessedEvent({ $browser: 'Chrome' }, { uuid: 'regular-1', event: '$pageview' })
-
- const result = await step({
- eventsToEmit: [
- { event: aiEvent, output: EVENTS_OUTPUT },
- { event: regularEvent, output: EVENTS_OUTPUT },
- ],
- teamId: 1,
- })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
-
- const { eventsToEmit } = result.value
- expect(eventsToEmit).toHaveLength(3)
-
- expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
- expect(eventsToEmit[0].event.properties).not.toHaveProperty('$ai_input')
- expect(eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
- expect(eventsToEmit[1].event.properties).toHaveProperty('$ai_input', 'large')
- expect(eventsToEmit[2].event).toBe(regularEvent)
- expect(eventsToEmit[2].output).toBe(EVENTS_OUTPUT)
- })
-
- it('should handle AI event with empty properties', async () => {
- const event = createProcessedEvent({})
-
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
-
- // $ai_generation is an AI event, so it goes to both outputs
- expect(result.value.eventsToEmit).toHaveLength(2)
- expect(result.value.eventsToEmit[0].event).toBe(event)
- expect(result.value.eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
- expect(result.value.eventsToEmit[1].event).toBe(event)
- expect(result.value.eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
- })
-
- it('should handle non-AI event with empty properties', async () => {
- const event = createProcessedEvent({}, { event: '$pageview' })
-
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
-
- expect(result.value.eventsToEmit).toHaveLength(1)
- expect(result.value.eventsToEmit[0].event).toBe(event)
- })
-
- it('should handle undefined properties on non-AI event', async () => {
- const event = createProcessedEvent({}, { event: '$pageview' })
- event.properties = undefined as any
-
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
-
- expect(result.value.eventsToEmit).toHaveLength(1)
- expect(result.value.eventsToEmit[0].event).toBe(event)
- })
-
- it('should handle empty input', async () => {
- const result = await step({ eventsToEmit: [], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
-
- expect(result.value.eventsToEmit).toHaveLength(0)
- })
-
- it('should copy for main output and keep original for AI output', async () => {
- const event = createProcessedEvent({ $ai_input: 'large input', $ai_model: 'gpt-4' })
-
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
-
- const { eventsToEmit } = result.value
- expect(eventsToEmit).toHaveLength(2)
-
- // Main output entry is a copy with stripped properties
- expect(eventsToEmit[0].event).not.toBe(event)
- expect(eventsToEmit[0].event.properties).not.toHaveProperty('$ai_input')
+ }
+ )
+
+ it.each([
+ { props: { $browser: 'Chrome' }, desc: 'without large AI properties' },
+ { props: { $browser: 'Chrome', $ai_input: 'large input' }, desc: 'with large AI properties' },
+ ])('should pass through non-AI event $desc to single output', async ({ props }) => {
+ const event = createProcessedEvent(props, { event: '$pageview' })
+
+ const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
+ expect(isOkResult(result)).toBe(true)
+ if (!isOkResult(result)) {
+ return
+ }
- // AI output entry keeps the original event object
- expect(eventsToEmit[1].event).toBe(event)
- })
+ const { eventsToEmit } = result.value
+ expect(eventsToEmit).toHaveLength(1)
+ expect(eventsToEmit[0].event).toBe(event)
+ expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
})
- describe('non-stripping mode (stripHeavyTeams empty array)', () => {
- const step = createSplitAiEventsStep(ENABLED_NO_STRIP)
-
- it('should send AI event with heavy properties unchanged to both outputs', async () => {
- const event = createProcessedEvent({
- $ai_input: 'large input',
- $ai_output: 'large output',
- $ai_model: 'gpt-4',
- })
-
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
-
- const { eventsToEmit } = result.value
- expect(eventsToEmit).toHaveLength(2)
-
- // Both outputs get the same unchanged event
- expect(eventsToEmit[0].event).toBe(event)
- expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
- expect(eventsToEmit[0].event.properties).toHaveProperty('$ai_input', 'large input')
+ it('should handle multiple events independently', async () => {
+ const aiEvent = createProcessedEvent({ $ai_input: 'large', $ai_model: 'gpt-4' }, { uuid: 'ai-1' })
+ const regularEvent = createProcessedEvent({ $browser: 'Chrome' }, { uuid: 'regular-1', event: '$pageview' })
- expect(eventsToEmit[1].event).toBe(event)
- expect(eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
- expect(eventsToEmit[1].event.properties).toHaveProperty('$ai_input', 'large input')
+ const result = await step({
+ eventsToEmit: [
+ { event: aiEvent, output: EVENTS_OUTPUT },
+ { event: regularEvent, output: EVENTS_OUTPUT },
+ ],
+ teamId: 1,
})
+ expect(isOkResult(result)).toBe(true)
+ if (!isOkResult(result)) {
+ return
+ }
- it('should still pass through non-AI events unchanged', async () => {
- const event = createProcessedEvent({ $browser: 'Chrome' }, { event: '$pageview' })
+ const { eventsToEmit } = result.value
+ expect(eventsToEmit).toHaveLength(3)
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
-
- expect(result.value.eventsToEmit).toHaveLength(1)
- expect(result.value.eventsToEmit[0].event).toBe(event)
- })
+ expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
+ expect(eventsToEmit[0].event.properties).not.toHaveProperty('$ai_input')
+ expect(eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
+ expect(eventsToEmit[1].event.properties).toHaveProperty('$ai_input', 'large')
+ expect(eventsToEmit[2].event).toBe(regularEvent)
+ expect(eventsToEmit[2].output).toBe(EVENTS_OUTPUT)
+ })
- it('should send AI event without heavy properties to both outputs', async () => {
- const event = createProcessedEvent({ $ai_model: 'gpt-4' })
+ it('should handle AI event with empty properties', async () => {
+ const event = createProcessedEvent({})
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
+ const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
+ expect(isOkResult(result)).toBe(true)
+ if (!isOkResult(result)) {
+ return
+ }
- const { eventsToEmit } = result.value
- expect(eventsToEmit).toHaveLength(2)
- expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
- expect(eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
- })
+ // $ai_generation is an AI event, so it goes to both outputs
+ expect(result.value.eventsToEmit).toHaveLength(2)
+ expect(result.value.eventsToEmit[0].event).toBe(event)
+ expect(result.value.eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
+ expect(result.value.eventsToEmit[1].event).toBe(event)
+ expect(result.value.eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
})
- describe('per-team strip allowlist', () => {
- const step = createSplitAiEventsStep({
- enabled: true,
- enabledTeams: '*',
- enabledPercentage: 0,
- stripHeavyTeams: [2],
- })
+ it('should handle non-AI event with empty properties', async () => {
+ const event = createProcessedEvent({}, { event: '$pageview' })
- it('should strip heavy props for a team in stripHeavyTeams', async () => {
- const event = createProcessedEvent({ $ai_input: 'large input', $ai_model: 'gpt-4' })
-
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 2 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
+ const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
+ expect(isOkResult(result)).toBe(true)
+ if (!isOkResult(result)) {
+ return
+ }
- const { eventsToEmit } = result.value
- expect(eventsToEmit).toHaveLength(2)
- expect(eventsToEmit[0].output).toBe(EVENTS_OUTPUT)
- expect(eventsToEmit[0].event.properties).not.toHaveProperty('$ai_input')
- expect(eventsToEmit[1].output).toBe(AI_EVENTS_OUTPUT)
- expect(eventsToEmit[1].event.properties).toHaveProperty('$ai_input', 'large input')
- })
+ expect(result.value.eventsToEmit).toHaveLength(1)
+ expect(result.value.eventsToEmit[0].event).toBe(event)
+ })
- it('should double-write unchanged for teams not in stripHeavyTeams', async () => {
- const event = createProcessedEvent({ $ai_input: 'large input', $ai_model: 'gpt-4' })
+ it('should handle undefined properties on non-AI event', async () => {
+ const event = createProcessedEvent({}, { event: '$pageview' })
+ event.properties = undefined as any
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
- expect(isOkResult(result)).toBe(true)
- if (!isOkResult(result)) {
- return
- }
+ const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
+ expect(isOkResult(result)).toBe(true)
+ if (!isOkResult(result)) {
+ return
+ }
- const { eventsToEmit } = result.value
- expect(eventsToEmit).toHaveLength(2)
- expect(eventsToEmit[0].event).toBe(event)
- expect(eventsToEmit[0].event.properties).toHaveProperty('$ai_input', 'large input')
- expect(eventsToEmit[1].event).toBe(event)
- expect(eventsToEmit[1].event.properties).toHaveProperty('$ai_input', 'large input')
- })
+ expect(result.value.eventsToEmit).toHaveLength(1)
+ expect(result.value.eventsToEmit[0].event).toBe(event)
})
- describe('percentage rollout', () => {
- async function runForTeam(config: SplitAiEventsStepConfig, teamId: number): Promise<number> {
- const step = createSplitAiEventsStep(config)
- const event = createProcessedEvent({ $ai_input: 'x', $ai_model: 'gpt-4' })
- const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId })
- if (!isOkResult(result)) {
- throw new Error('expected ok result')
- }
- return result.value.eventsToEmit.length
+ it('should handle empty input', async () => {
+ const result = await step({ eventsToEmit: [], teamId: 1 })
+ expect(isOkResult(result)).toBe(true)
+ if (!isOkResult(result)) {
+ return
}
- it('routes no team when percentage is 0 and team list is empty', async () => {
- const config: SplitAiEventsStepConfig = {
- enabled: true,
- enabledTeams: [],
- enabledPercentage: 0,
- stripHeavyTeams: [],
- }
- for (const teamId of [1, 2, 3, 99, 1234]) {
- expect(await runForTeam(config, teamId)).toBe(1)
- }
- })
-
- it('routes every team when percentage is 100', async () => {
- const config: SplitAiEventsStepConfig = {
- enabled: true,
- enabledTeams: [],
- enabledPercentage: 100,
- stripHeavyTeams: [],
- }
- for (const teamId of [1, 2, 3, 99, 1234]) {
- expect(await runForTeam(config, teamId)).toBe(2)
- }
- })
-
- it('rollout is monotonic — every team in at X% stays in at any Y% > X%', async () => {
- const teamIds = Array.from({ length: 1000 }, (_, i) => i + 1)
- const inAt: Record<number, Set<number>> = {}
- for (const pct of [10, 25, 50, 75, 90, 100]) {
- const config: SplitAiEventsStepConfig = {
- enabled: true,
- enabledTeams: [],
- enabledPercentage: pct,
- stripHeavyTeams: [],
- }
- inAt[pct] = new Set()
- for (const teamId of teamIds) {
- if ((await runForTeam(config, teamId)) === 2) {
- inAt[pct].add(teamId)
- }
- }
- }
- for (const [lo, hi] of [
- [10, 25],
- [25, 50],
- [50, 75],
- [75, 90],
- [90, 100],
- ]) {
- for (const teamId of inAt[lo]) {
- expect(inAt[hi].has(teamId)).toBe(true)
- }
- }
- })
+ expect(result.value.eventsToEmit).toHaveLength(0)
+ })
- it('rollout bucket distribution stays close to the configured percentage', async () => {
- const teamIds = Array.from({ length: 10_000 }, (_, i) => i + 1)
- const config: SplitAiEventsStepConfig = {
- enabled: true,
- enabledTeams: [],
- enabledPercentage: 25,
- stripHeavyTeams: [],
- }
- let routed = 0
- for (const teamId of teamIds) {
- if ((await runForTeam(config, teamId)) === 2) {
- routed++
- }
- }
- const ratio = routed / teamIds.length
- expect(ratio).toBeGreaterThan(0.22)
- expect(ratio).toBeLessThan(0.28)
- })
+ it('should copy for main output and keep original for AI output', async () => {
+ const event = createProcessedEvent({ $ai_input: 'large input', $ai_model: 'gpt-4' })
- it('union: explicit team is always routed, even when its bucket falls outside the percentage', async () => {
- // Team 2's bucket is 26 — at percentage 10 it would be excluded by hash alone.
- const config: SplitAiEventsStepConfig = {
- enabled: true,
- enabledTeams: [2],
- enabledPercentage: 10,
- stripHeavyTeams: [],
- }
- expect(await runForTeam(config, 2)).toBe(2)
- })
+ const result = await step({ eventsToEmit: [{ event, output: EVENTS_OUTPUT }], teamId: 1 })
+ expect(isOkResult(result)).toBe(true)
+ if (!isOkResult(result)) {
+ return
+ }
- it('union: percentage routes additional teams beyond the explicit list', async () => {
- const config: SplitAiEventsStepConfig = {
- enabled: true,
- enabledTeams: [2],
- enabledPercentage: 50,
- stripHeavyTeams: [],
- }
- // teamId 5 → bucket 17 (under 50%); not in the explicit list
- expect(await runForTeam(config, 5)).toBe(2)
- // teamId 2 → in the explicit list
- expect(await runForTeam(config, 2)).toBe(2)
- // teamId 3 → bucket 87 (above 50%); not in the explicit list
- expect(await runForTeam(config, 3)).toBe(1)
- })
+ const { eventsToEmit } = result.value
+ expect(eventsToEmit).toHaveLength(2)
- it("'*' routes everything regardless of percentage", async () => {
- const config: SplitAiEventsStepConfig = {
- enabled: true,
- enabledTeams: '*',
- enabledPercentage: 0,
- stripHeavyTeams: [],
- }
- expect(await runForTeam(config, 1)).toBe(2)
- expect(await runForTeam(config, 999_999)).toBe(2)
- })
+ // Main output entry is a copy with stripped properties
+ expect(eventsToEmit[0].event).not.toBe(event)
+ expect(eventsToEmit[0].event.properties).not.toHaveProperty('$ai_input')
- it('bucketing stays stable for team ids past the f64-precision threshold (~3.4M)', async () => {
- // Without Math.imul, `teamId * 2654435761` loses precision past 2^53, shifting
- // the bucket by ±1 for teamIds ≳ 3.4M. teamId 3_393_265 lands in bucket 77
- // under the corrected implementation; the naive multiplication would produce 76.
- const noRollout: SplitAiEventsStepConfig = {
- enabled: true,
- enabledTeams: [],
- enabledPercentage: 77,
- stripHeavyTeams: [],
- }
- const fullRollout: SplitAiEventsStepConfig = {
- enabled: true,
- enabledTeams: [],
- enabledPercentage: 78,
- stripHeavyTeams: [],
- }
- // bucket 77, threshold 77 → not routed; threshold 78 → routed.
- expect(await runForTeam(noRollout, 3_393_265)).toBe(1)
- expect(await runForTeam(fullRollout, 3_393_265)).toBe(2)
- // High teamIds still respect 0% and 100% boundaries.
- for (const teamId of [10_000_000, 50_000_000, 99_999_999]) {
- expect(await runForTeam({ ...noRollout, enabledPercentage: 0 }, teamId)).toBe(1)
- expect(await runForTeam({ ...noRollout, enabledPercentage: 100 }, teamId)).toBe(2)
- }
- })
+ // AI output entry keeps the original event object
+ expect(eventsToEmit[1].event).toBe(event)
})
})
diff --git a/nodejs/src/ingestion/common/steps/event-processing/split-ai-events-step.ts b/nodejs/src/ingestion/common/steps/event-processing/split-ai-events-step.ts
index 5ae7438f928a..1fc9ae1a8e06 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/split-ai-events-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/split-ai-events-step.ts
@@ -3,7 +3,6 @@ import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'
import { ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
import { ProcessedEvent } from '~/types'
-import { parseTeamsList } from '~/utils/env-utils'
import { EventToEmit } from './emit-event-step'
@@ -16,27 +15,6 @@ const LARGE_AI_PROPERTIES = new Set([
'$ai_tools',
])
-export interface SplitAiEventsStepConfig {
- enabled: boolean
- /**
- * '*' for all teams, or a small array of always-routed team IDs.
- * Hot-path lookup uses Array.includes; expected size is ~3–10, which beats Set in V8.
- */
- enabledTeams: number[] | '*'
- /**
- * Sticky percentage rollout (0-100), unioned with enabledTeams. A team is routed if it's
- * in the allowlist OR its bucket falls under the percentage. Bucketing is deterministic on
- * team_id, so the rollout is monotonic — every team in at X% stays in at any Y% > X%.
- */
- enabledPercentage: number
- /**
- * Teams whose events copy should have heavy AI properties stripped — i.e. the post-migration final state
- * where heavy columns live only in the AI events table. '*' for all teams, or a small array of team IDs.
- * Teams not listed here keep double-writing the full event to both outputs.
- */
- stripHeavyTeams: number[] | '*'
-}
-
export interface SplitAiEventsStepInput {
eventsToEmit: EventToEmit<EventOutput>[]
teamId: number
@@ -55,23 +33,20 @@ function hasLargeAiProperties(properties: Record<string, unknown>): boolean {
return false
}
-function maybeStripAiProperties(
- entry: EventToEmit<EventOutput>,
- stripHeavyForTeam: boolean
-): EventToEmit<EventOutput | AiEventOutput>[] {
+function splitAiEvent(entry: EventToEmit<EventOutput>): EventToEmit<EventOutput | AiEventOutput>[] {
const properties = entry.event.properties ?? {}
- const isAiEvent = AI_EVENT_TYPES.has(entry.event.event)
- if (!isAiEvent) {
+ if (!AI_EVENT_TYPES.has(entry.event.event)) {
return [entry]
}
- if (!stripHeavyForTeam || !hasLargeAiProperties(properties)) {
- // Duplicate unchanged to both outputs
+ if (!hasLargeAiProperties(properties)) {
+ // Nothing heavy to strip — duplicate unchanged to both outputs.
return [entry, { event: entry.event, output: AI_EVENTS_OUTPUT }]
}
- // Strip heavy props from events copy (only when team is in stripHeavyTeams)
+ // The heavy AI properties live only on the dedicated ai_events table, so strip them
+ // from the events copy and send the full event to AI_EVENTS_OUTPUT.
const stripped: Record<string, unknown> = {}
for (const [key, value] of Object.entries(properties)) {
if (!LARGE_AI_PROPERTIES.has(key)) {
@@ -87,65 +62,15 @@ function maybeStripAiProperties(
]
}
-function clampPercentage(pct: number): number {
- if (Number.isNaN(pct) || pct <= 0) {
- return 0
- }
- if (pct >= 100) {
- return 100
- }
- return pct
-}
-
-/**
- * Stable bucket [0, 99] for a team id. Knuth's multiplicative hash so consecutive
- * team ids don't cluster into the same bucket.
- */
-function teamRolloutBucket(teamId: number): number {
- return (Math.imul(teamId, 2654435761) >>> 0) % 100
-}
-
-function isTeamRouted(teams: number[] | '*', percentage: number, teamId: number): boolean {
- if (teams === '*' || percentage >= 100) {
- return true
- }
- if (teams.includes(teamId)) {
- return true
- }
- if (percentage <= 0) {
- return false
- }
- return teamRolloutBucket(teamId) < percentage
-}
-
-export function parseSplitAiEventsConfig(
- enabled: boolean,
- teamsStr: string,
- stripHeavyTeamsStr: string,
- percentage: number = 0
-): SplitAiEventsStepConfig {
- return {
- enabled,
- enabledTeams: parseTeamsList(teamsStr),
- enabledPercentage: clampPercentage(percentage),
- stripHeavyTeams: parseTeamsList(stripHeavyTeamsStr),
- }
-}
-
-export function createSplitAiEventsStep<T extends SplitAiEventsStepInput>(
- config: SplitAiEventsStepConfig
-): ProcessingStep<T, T & SplitAiEventsStepOutput> {
+export function createSplitAiEventsStep<T extends SplitAiEventsStepInput>(): ProcessingStep<
+ T,
+ T & SplitAiEventsStepOutput
+> {
return function splitAiEventsStep(input) {
- if (!config.enabled || !isTeamRouted(config.enabledTeams, config.enabledPercentage, input.teamId)) {
- return Promise.resolve(ok(input))
- }
-
- const stripHeavyForTeam = config.stripHeavyTeams === '*' || config.stripHeavyTeams.includes(input.teamId)
-
return Promise.resolve(
ok({
...input,
- eventsToEmit: input.eventsToEmit.flatMap((entry) => maybeStripAiProperties(entry, stripHeavyForTeam)),
+ eventsToEmit: input.eventsToEmit.flatMap((entry) => splitAiEvent(entry)),
})
)
}
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index 253153efc745..e002fcc1af08 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -166,22 +166,6 @@ export type IngestionConsumerConfig = {
INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_HOST: string
INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_PORT: number
- // AI event splitting config
- INGESTION_AI_EVENT_SPLITTING_ENABLED: boolean
- /** '*' for all teams, or comma-separated team IDs always routed to ai_events */
- INGESTION_AI_EVENT_SPLITTING_TEAMS: string
- /**
- * Sticky percentage rollout (0-100), unioned with INGESTION_AI_EVENT_SPLITTING_TEAMS.
- * Bucketed deterministically on team_id so increases are monotonic and per-team writes don't flap.
- */
- INGESTION_AI_EVENT_SPLITTING_PERCENTAGE: number
- /**
- * Teams whose events copy should have heavy AI properties stripped — i.e. the post-migration final state
- * where heavy columns live only in the AI events table. '*' for all teams, or comma-separated team IDs.
- * Defaults to '' (no stripping → double-write the full event for everyone).
- */
- INGESTION_AI_EVENT_SPLITTING_STRIP_HEAVY_TEAMS: string
-
// Clickhouse topics
CLICKHOUSE_JSON_EVENTS_KAFKA_TOPIC: string
CLICKHOUSE_AI_EVENTS_KAFKA_TOPIC: string
@@ -290,12 +274,6 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_HOST: '',
INGESTION_FEATURE_FLAG_CALLED_DEDUP_REDIS_PORT: 6379,
- // AI event splitting config
- INGESTION_AI_EVENT_SPLITTING_ENABLED: false,
- INGESTION_AI_EVENT_SPLITTING_TEAMS: '*',
- INGESTION_AI_EVENT_SPLITTING_PERCENTAGE: 0,
- INGESTION_AI_EVENT_SPLITTING_STRIP_HEAVY_TEAMS: '',
-
// Clickhouse topics
CLICKHOUSE_JSON_EVENTS_KAFKA_TOPIC: KAFKA_EVENTS_JSON,
CLICKHOUSE_AI_EVENTS_KAFKA_TOPIC: KAFKA_CLICKHOUSE_AI_EVENTS_JSON,
diff --git a/nodejs/src/ingestion/ingestion-consumer.test.ts b/nodejs/src/ingestion/ingestion-consumer.test.ts
index 0c8fdab5886e..b1b4f1a10d3b 100644
--- a/nodejs/src/ingestion/ingestion-consumer.test.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.test.ts
@@ -917,11 +917,8 @@ describe('IngestionConsumer', () => {
expect(nonAiEvent?.value.distinct_id).toBe('user-non-ai')
})
- it('should split AI events with large properties when splitting is enabled', async () => {
+ it('should split AI events with large properties into events + ai_events', async () => {
await ingester.stop()
- infra.config.INGESTION_AI_EVENT_SPLITTING_ENABLED = true
- infra.config.INGESTION_AI_EVENT_SPLITTING_TEAMS = '*'
- infra.config.INGESTION_AI_EVENT_SPLITTING_STRIP_HEAVY_TEAMS = '*'
ingester = await createIngestionConsumer(infra)
const events = [
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index 114420689405..351199ae6eca 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -29,7 +29,6 @@ import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-mana
import { BatchWritingGroupStore } from '~/ingestion/common/groups/batch-writing-group-store'
import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'
import { PersonsStore } from '~/ingestion/common/persons/persons-store'
-import { parseSplitAiEventsConfig } from '~/ingestion/common/steps/event-processing/split-ai-events-step'
import { createOkContext } from '~/ingestion/framework/helpers'
import { TopHog } from '~/ingestion/framework/tophog'
import {
@@ -278,12 +277,6 @@ export class IngestionConsumer {
personsPrefetchEnabled: this.config.PERSONS_PREFETCH_ENABLED,
cdpHogWatcherSampleRate: this.config.CDP_HOG_WATCHER_SAMPLE_RATE,
outputs,
- splitAiEventsConfig: parseSplitAiEventsConfig(
- this.config.INGESTION_AI_EVENT_SPLITTING_ENABLED,
- this.config.INGESTION_AI_EVENT_SPLITTING_TEAMS,
- this.config.INGESTION_AI_EVENT_SPLITTING_STRIP_HEAVY_TEAMS,
- this.config.INGESTION_AI_EVENT_SPLITTING_PERCENTAGE
- ),
perDistinctIdOptions: {
SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP: this.config.SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP,
PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: this.config.PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT,
diff --git a/nodejs/src/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.ts
index cad3735988c2..021e06030141 100644
--- a/nodejs/src/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.ts
@@ -23,7 +23,7 @@ export function createAiEventSubpipeline<TInput extends AiEventSubpipelineInput,
builder: StartPipelineBuilder<TInput, TContext>,
config: AiEventSubpipelineConfig
): PipelineBuilder<TInput, EmitEventStepOutput, TContext, AsyncOutput> {
- const { options, outputs, teamManager, groupTypeManager, hogTransformer, splitAiEventsConfig, topHog } = config
+ const { options, outputs, teamManager, groupTypeManager, hogTransformer, topHog } = config
return builder
.pipe(createNormalizeProcessPersonFlagStep())
@@ -71,7 +71,7 @@ export function createAiEventSubpipeline<TInput extends AiEventSubpipelineInput,
.pipe(createPrepareEventStep())
.pipe(createProcessGroupsStep(teamManager, groupTypeManager, options))
.pipe(createCreateEventStep(EVENTS_OUTPUT))
- .pipe(createSplitAiEventsStep(splitAiEventsConfig))
+ .pipe(createSplitAiEventsStep())
.pipe(
topHog(
createEmitEventStep({
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index ae4bccbc0e26..61aa0512371c 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -28,7 +28,6 @@ import {
import { EmitEventStepOutput } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { EventPipelineRunnerOptions } from '~/ingestion/common/steps/event-processing/event-pipeline-options'
import { createFlushBatchStoresStep } from '~/ingestion/common/steps/event-processing/flush-batch-stores-step'
-import { SplitAiEventsStepConfig } from '~/ingestion/common/steps/event-processing/split-ai-events-step'
import {
GroupStoreBatchContext,
createGroupStoreBeforeBatchStep,
@@ -86,7 +85,6 @@ export interface JoinedIngestionPipelineConfig {
| PersonMergeEventsOutput
| AppMetricsOutput
>
- splitAiEventsConfig: SplitAiEventsStepConfig
perDistinctIdOptions: EventPipelineRunnerOptions
/**
* Maximum number of batches the BatchingPipeline will accept concurrently.
@@ -155,7 +153,6 @@ export function createJoinedIngestionPipeline<
personsPrefetchEnabled,
cdpHogWatcherSampleRate,
outputs,
- splitAiEventsConfig,
perDistinctIdOptions,
concurrentBatches,
} = config
@@ -204,7 +201,6 @@ export function createJoinedIngestionPipeline<
const perEventConfig: PerDistinctIdPipelineConfig = {
options: perDistinctIdOptions,
outputs,
- splitAiEventsConfig,
aiSubpipelineFactory,
teamManager,
groupTypeManager,
diff --git a/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts
index 6ee8a1ee4486..427497b383f5 100644
--- a/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts
@@ -8,7 +8,6 @@ import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'
import { AiEventSubpipelineFactory, AiEventSubpipelineInput } from '~/ingestion/common/ai-subpipeline.contract'
import { EmitEventStepOutput } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { EventPipelineRunnerOptions } from '~/ingestion/common/steps/event-processing/event-pipeline-options'
-import { SplitAiEventsStepConfig } from '~/ingestion/common/steps/event-processing/split-ai-events-step'
import { PipelineBuilder, StartPipelineBuilder } from '~/ingestion/framework/builders/pipeline-builders'
import { TopHogWrapper } from '~/ingestion/framework/extensions/tophog'
import { Team } from '~/types'
@@ -36,7 +35,6 @@ export interface PerDistinctIdPipelineConfig {
| PersonDistinctIdsOutput
| PersonMergeEventsOutput
>
- splitAiEventsConfig: SplitAiEventsStepConfig
aiSubpipelineFactory: AiEventSubpipelineFactory
teamManager: TeamManager
groupTypeManager: GroupTypeManager
@@ -63,16 +61,7 @@ export function createPerDistinctIdPipeline<TInput extends PerDistinctIdPipeline
builder: StartPipelineBuilder<TInput, TContext>,
config: PerDistinctIdPipelineConfig
): PipelineBuilder<TInput, EmitEventStepOutput, TContext, AsyncOutput> {
- const {
- options,
- outputs,
- splitAiEventsConfig,
- aiSubpipelineFactory,
- teamManager,
- groupTypeManager,
- hogTransformer,
- topHog,
- } = config
+ const { options, outputs, aiSubpipelineFactory, teamManager, groupTypeManager, hogTransformer, topHog } = config
return builder.retry(
(e) =>
@@ -85,7 +74,6 @@ export function createPerDistinctIdPipeline<TInput extends PerDistinctIdPipeline
teamManager,
groupTypeManager,
hogTransformer,
- splitAiEventsConfig,
topHog,
})
)
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index 68c69d94cbb6..940a24be1102 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -20,7 +20,6 @@ import {
getDefaultKafkaDownstreamProducerEnvConfig,
getDefaultKafkaUpstreamProducerEnvConfig,
} from '~/ingestion/common/producers'
-import { parseSplitAiEventsConfig } from '~/ingestion/common/steps/event-processing/split-ai-events-step'
import { createOkContext } from '~/ingestion/framework/helpers'
import { TopHog } from '~/ingestion/framework/tophog'
import { createAiEventSubpipeline } from '~/ingestion/pipelines/ai'
@@ -366,12 +365,6 @@ export class IngestionApiServer implements NodeServer {
personsPrefetchEnabled: this.config.PERSONS_PREFETCH_ENABLED,
cdpHogWatcherSampleRate: this.config.CDP_HOG_WATCHER_SAMPLE_RATE,
outputs: ingestionOutputs,
- splitAiEventsConfig: parseSplitAiEventsConfig(
- this.config.INGESTION_AI_EVENT_SPLITTING_ENABLED,
- this.config.INGESTION_AI_EVENT_SPLITTING_TEAMS,
- this.config.INGESTION_AI_EVENT_SPLITTING_STRIP_HEAVY_TEAMS,
- this.config.INGESTION_AI_EVENT_SPLITTING_PERCENTAGE
- ),
perDistinctIdOptions: {
SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP: this.config.SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP,
PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: this.config.PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT,
diff --git a/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts b/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts
index fc28ab67ee27..db25bbf64568 100644
--- a/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts
+++ b/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts
@@ -110,12 +110,6 @@ function buildPipeline(configOverrides: Partial<AiEventSubpipelineConfig> = {})
hogTransformer: {
transformEventAndProduceMessages: (event: PluginEvent) => Promise.resolve({ event, invocationResults: [] }),
} as any,
- splitAiEventsConfig: {
- enabled: false,
- enabledTeams: '*',
- enabledPercentage: 0,
- stripHeavyTeams: [],
- },
topHog: (step) => step,
...configOverrides,
}
@@ -146,15 +140,17 @@ type AiOutputs =
| typeof PERSON_DISTINCT_IDS_OUTPUT
| typeof PERSON_MERGE_EVENTS_OUTPUT
-function getProduceCall(mockOutputs: jest.Mocked<IngestionOutputs<AiOutputs>>) {
- expect(mockOutputs.produce).toHaveBeenCalledTimes(1)
- const outputName = mockOutputs.produce.mock.calls[0][0]
- const call = mockOutputs.produce.mock.calls[0][1]
- const event = parseJSON(call.value!.toString())
+function getProduceCall(mockOutputs: jest.Mocked<IngestionOutputs<AiOutputs>>, output: AiOutputs = EVENTS_OUTPUT) {
+ const call = mockOutputs.produce.mock.calls.find(([outputName]) => outputName === output)
+ if (!call) {
+ throw new Error(`No produce call for output ${output}`)
+ }
+ const [outputName, message] = call
+ const event = parseJSON(message.value!.toString())
return {
outputName: outputName as string,
- key: call.key as string,
- headers: call.headers as Record<string, string>,
+ key: message.key as string,
+ headers: message.headers as Record<string, string>,
event,
properties: parseJSON(event.properties) as Record<string, unknown>,
}
@@ -195,6 +191,10 @@ describe('AI event subpipeline integration', () => {
// Emit step: correct output
expect(outputName).toBe(EVENTS_OUTPUT)
+ // Split step: AI events are unconditionally duplicated to the dedicated ai_events output
+ expect(mockOutputs.produce).toHaveBeenCalledTimes(2)
+ expect(getProduceCall(mockOutputs, AI_EVENTS_OUTPUT).event.event).toBe('$ai_generation')
+
// Event identity preserved
expect(produced.event).toBe('$ai_generation')
expect(produced.team_id).toBe(team.id)
diff --git a/posthog/hogql_queries/ai/ai_column_rewriter.py b/posthog/hogql_queries/ai/ai_column_rewriter.py
index dc926062735e..0f226e390ff3 100644
--- a/posthog/hogql_queries/ai/ai_column_rewriter.py
+++ b/posthog/hogql_queries/ai/ai_column_rewriter.py
@@ -1,8 +1,7 @@
"""AST rewriter that translates queries written against `ai_events` columns to work with the `events` table.
This is the reverse of `AiPropertyRewriter`. When a query targets the `events` table
-as a fallback (e.g. data older than the `ai_events` TTL, or the kill switch is off),
-this rewriter:
+as a fallback (e.g. data older than the `ai_events` retention TTL), this rewriter:
1. Rewrites dedicated column references (e.g. `trace_id`) to property access
(e.g. `properties.$ai_trace_id`) so they resolve against the `events` table.
diff --git a/posthog/hogql_queries/ai/ai_table_resolver.py b/posthog/hogql_queries/ai/ai_table_resolver.py
index 27a76f645c6c..d98971398632 100644
--- a/posthog/hogql_queries/ai/ai_table_resolver.py
+++ b/posthog/hogql_queries/ai/ai_table_resolver.py
@@ -2,7 +2,6 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any
-import posthoganalytics
from prometheus_client import Counter, Histogram
from posthog.hogql import ast
@@ -14,13 +13,13 @@ from posthog.hogql_queries.ai.ai_property_rewriter import rewrite_expr_for_ai_ev
AI_EVENTS_QUERY_TOTAL = Counter(
"posthog_ai_events_query_total",
- "AI observability queries routed by execute_with_ai_events_fallback, by read-path source.",
+ "AI observability queries routed by query_ai_events, by read-path outcome.",
labelnames=["source"],
)
AI_EVENTS_QUERY_DURATION_SECONDS = Histogram(
"posthog_ai_events_query_duration_seconds",
- "Wall-clock duration of AI observability query executions, by read-path source. Used to compare dedicated_table vs shared_table latency.",
+ "Wall-clock duration of AI observability query executions, by read-path source.",
labelnames=["source"],
buckets=(0.025, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30),
)
@@ -34,39 +33,48 @@ if TYPE_CHECKING:
from posthog.models import Team
-def is_ai_events_enabled(team: Team) -> bool:
- """Kill switch for ai_events table reads.
+class AIEventsUnavailableError(Exception):
+ """The requested AI events could not be served from the dedicated ai_events table
+ and the caller opted out of the events fallback (``fall_back_to_events=False``)."""
+
+
+class AIEventsExpiredError(AIEventsUnavailableError):
+ """The requested AI events exist in the shared events table but have aged out of
+ ai_events (past its retention TTL)."""
- When disabled, all single-trace runners skip the ai_events attempt
- and query the events table directly.
- """
- return posthoganalytics.feature_enabled(
- "ai-events-table-rollout",
- str(team.id),
- groups={"organization": str(team.organization_id)},
- group_properties={"organization": {"id": str(team.organization_id)}},
- send_feature_flag_events=False,
- )
+class AIEventsNotFoundError(AIEventsUnavailableError):
+ """The requested AI events were not found in either ai_events or the shared events table."""
-def execute_with_ai_events_fallback(
+
+def query_ai_events(
query: ast.SelectQuery | ast.SelectSetQuery,
placeholders: dict[str, ast.Expr],
team: Team,
query_type: str,
+ *,
+ fall_back_to_events: bool = False,
timings: HogQLTimings | None = None,
modifiers: HogQLQueryModifiers | None = None,
limit_context: LimitContext | None = None,
settings: HogQLGlobalSettings | None = None,
workload: Workload | None = None,
) -> Any:
- """Execute a query written against ai_events, falling back to events if no results.
+ """Execute a query written against the dedicated ai_events table.
+
+ Queries should be written against ai_events using native column names. Placeholders
+ may contain properties.$ai_* references (e.g. from property filters); they are
+ rewritten to native columns for ai_events and back to properties.$ai_* when the query
+ runs against the shared events table.
- Queries should be written against the ai_events table with native column names.
- Placeholders may contain properties.$ai_* references (e.g. from property filters)
- which are rewritten to native columns for ai_events and back for the events fallback.
+ ai_events has a 30-day retention TTL; the shared events table is long-lived but has the
+ heavy AI columns stripped. When ai_events returns no rows:
- When the kill switch (is_ai_events_enabled) is off, skips the ai_events attempt entirely.
+ - ``fall_back_to_events=True``: re-run against events and return that result. Use this
+ for paths that stay useful without the heavy columns (trace shape, costs, navigation).
+ - ``fall_back_to_events=False`` (default): an events row would be useless to the caller,
+ so events is probed only to classify the miss — raising :class:`AIEventsExpiredError`
+ (the data aged past the TTL) or :class:`AIEventsNotFoundError` (it never existed).
`workload` should be specified explicitly for batch / scheduled callers (e.g. usage
reports). Inside a Celery task the `task_prerun` signal sets `Workload.OFFLINE` on
@@ -87,32 +95,34 @@ def execute_with_ai_events_fallback(
kwargs["workload"] = workload
with tags_context(product=Product.LLM_ANALYTICS):
- if is_ai_events_enabled(team):
- tag_queries(ai_query_source="dedicated_table")
- ai_placeholders = {k: rewrite_expr_for_ai_events_table(v) for k, v in placeholders.items()}
- with AI_EVENTS_QUERY_DURATION_SECONDS.labels(source="dedicated_table").time():
- result = execute_hogql_query(query=query, placeholders=ai_placeholders, **kwargs)
- # Fallback: if ai_events returned no rows, re-run on the shared events table.
- # This handles the rollout window where older data may only exist in the shared
- # table. Only ~4% of queries fall outside the dedicated table's 30-day TTL
- # (https://us.posthog.com/project/2/insights/39oE9bLO), so for populated teams
- # the fallback fires rarely. Legitimately-empty queries do incur a redundant
- # second round-trip — acceptable during rollout, removed when the flag is retired.
- if result.results:
- AI_EVENTS_QUERY_TOTAL.labels(source="dedicated_table").inc()
- return result
- tag_queries(ai_query_source="shared_table_fallback")
- AI_EVENTS_QUERY_TOTAL.labels(source="shared_table_fallback").inc()
- fallback_source = "shared_table_fallback"
- else:
- tag_queries(ai_query_source="shared_table")
- AI_EVENTS_QUERY_TOTAL.labels(source="shared_table").inc()
- fallback_source = "shared_table"
+ tag_queries(ai_query_source="dedicated_table")
+ ai_placeholders = {k: rewrite_expr_for_ai_events_table(v) for k, v in placeholders.items()}
+ with AI_EVENTS_QUERY_DURATION_SECONDS.labels(source="dedicated_table").time():
+ result = execute_hogql_query(query=query, placeholders=ai_placeholders, **kwargs)
+ if result.results:
+ AI_EVENTS_QUERY_TOTAL.labels(source="dedicated_table").inc()
+ return result
events_query = rewrite_query_for_events_table(query)
events_placeholders = {k: rewrite_expr_for_events_table(v) for k, v in placeholders.items()}
- with AI_EVENTS_QUERY_DURATION_SECONDS.labels(source=fallback_source).time():
- return execute_hogql_query(query=events_query, placeholders=events_placeholders, **kwargs)
+
+ if fall_back_to_events:
+ tag_queries(ai_query_source="shared_table_fallback")
+ AI_EVENTS_QUERY_TOTAL.labels(source="shared_table_fallback").inc()
+ with AI_EVENTS_QUERY_DURATION_SECONDS.labels(source="shared_table_fallback").time():
+ return execute_hogql_query(query=events_query, placeholders=events_placeholders, **kwargs)
+
+ # The caller can't use heavy-column-stripped events rows, so probe events solely to
+ # tell "aged past the TTL" apart from "never existed" and raise the matching error.
+ with AI_EVENTS_QUERY_DURATION_SECONDS.labels(source="retention_probe").time():
+ probe = execute_hogql_query(query=events_query, placeholders=events_placeholders, **kwargs)
+ if probe.results:
+ tag_queries(ai_query_source="expired")
+ AI_EVENTS_QUERY_TOTAL.labels(source="expired").inc()
+ raise AIEventsExpiredError(f"AI events for {query_type} have aged past the ai_events retention window")
+ tag_queries(ai_query_source="not_found")
+ AI_EVENTS_QUERY_TOTAL.labels(source="not_found").inc()
+ raise AIEventsNotFoundError(f"AI events for {query_type} were not found")
# Canonical Python list. Node.js mirror: nodejs/src/ingestion/ai/process-ai-event.ts
diff --git a/posthog/hogql_queries/ai/test/__snapshots__/test_trace_query_runner.ambr b/posthog/hogql_queries/ai/test/__snapshots__/test_trace_query_runner.ambr
index bbb4d23e9b48..9a534fc05f9b 100644
--- a/posthog/hogql_queries/ai/test/__snapshots__/test_trace_query_runner.ambr
+++ b/posthog/hogql_queries/ai/test/__snapshots__/test_trace_query_runner.ambr
@@ -1,25 +1,25 @@
# serializer version: 1
# name: TestTraceQueryRunner.test_event_property_filters
'''
- SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '') AS id,
- any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_session_id'), ''), 'null'), '^"|"$', '')) AS ai_session_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS first_timestamp,
- max(toTimeZone(events.timestamp, 'UTC')) AS last_timestamp,
- ifNull(nullIf(argMinIf(events.distinct_id, toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$ai_trace')), ''), argMin(events.distinct_id, toTimeZone(events.timestamp, 'UTC'))) AS first_distinct_id,
- round(if(and(equals(countIf(and(ifNull(greater(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), 0), 0), notEquals(events.event, '$ai_generation'))), 0), greater(countIf(and(ifNull(greater(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), 0), 0), equals(events.event, '$ai_generation'))), 0)), sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), and(equals(events.event, '$ai_generation'), ifNull(greater(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), 0), 0))), sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), or(isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_parent_id'), ''), 'null'), '^"|"$', '')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_parent_id'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '')), isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_parent_id'), ''), 'null'), '^"|"$', ''))
- and isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '')))))), 2) AS total_latency,
- nullIf(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_tokens'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS input_tokens,
- nullIf(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_tokens'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS output_tokens,
- nullIf(round(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS input_cost,
- nullIf(round(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS output_cost,
- nullIf(round(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS total_cost,
- arrayDistinct(arraySort(x -> x.3, groupArrayIf(tuple(events.uuid, events.event, toTimeZone(events.timestamp, 'UTC'), events.properties, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_choices'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_state'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_state'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_tools'), ''), 'null'), '^"|"$', '')), notEquals(events.event, '$ai_trace')))) AS events,
- argMinIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_state'), ''), 'null'), '^"|"$', ''), toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$ai_trace')) AS input_state,
- argMinIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_state'), ''), 'null'), '^"|"$', ''), toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$ai_trace')) AS output_state,
- ifNull(argMinIf(ifNull(nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_span_name'), ''), 'null'), '^"|"$', ''), ''), nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_name'), ''), 'null'), '^"|"$', ''), '')), toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$ai_trace')), argMin(ifNull(nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_span_name'), ''), 'null'), '^"|"$', ''), ''), nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_name'), ''), 'null'), '^"|"$', ''), '')), toTimeZone(events.timestamp, 'UTC'))) AS trace_name
- FROM events
- WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', ''), 'trace1'), 0), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'bar'), 0)))
- GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '')
+ SELECT ai_events.trace_id AS id,
+ any(ai_events.session_id) AS ai_session_id,
+ min(toTimeZone(ai_events.timestamp, 'UTC')) AS first_timestamp,
+ max(toTimeZone(ai_events.timestamp, 'UTC')) AS last_timestamp,
+ ifNull(nullIf(argMinIf(ai_events.distinct_id, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')), ''), argMin(ai_events.distinct_id, toTimeZone(ai_events.timestamp, 'UTC'))) AS first_distinct_id,
+ round(if(and(equals(countIf(and(ifNull(greater(ai_events.latency, 0), 0), notEquals(ai_events.event, '$ai_generation'))), 0), greater(countIf(and(ifNull(greater(ai_events.latency, 0), 0), equals(ai_events.event, '$ai_generation'))), 0)), sumIf(ai_events.latency, and(equals(ai_events.event, '$ai_generation'), ifNull(greater(ai_events.latency, 0), 0))), sumIf(ai_events.latency, or(isNull(ai_events.parent_id), ifNull(equals(ai_events.parent_id, ai_events.trace_id), isNull(ai_events.parent_id)
+ and isNull(ai_events.trace_id))))), 2) AS total_latency,
+ nullIf(sumIf(ai_events.input_tokens, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS input_tokens,
+ nullIf(sumIf(ai_events.output_tokens, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS output_tokens,
+ nullIf(round(sumIf(ai_events.input_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS input_cost,
+ nullIf(round(sumIf(ai_events.output_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS output_cost,
+ nullIf(round(sumIf(ai_events.total_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS total_cost,
+ arrayDistinct(arraySort(x -> x.3, groupArrayIf(tuple(ai_events.uuid, ai_events.event, toTimeZone(ai_events.timestamp, 'UTC'), ai_events.properties, ai_events.input, ai_events.output, ai_events.output_choices, ai_events.input_state, ai_events.output_state, ai_events.tools), notEquals(ai_events.event, '$ai_trace')))) AS events,
+ argMinIf(ai_events.input_state, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')) AS input_state,
+ argMinIf(ai_events.output_state, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')) AS output_state,
+ ifNull(argMinIf(ifNull(nullIf(ai_events.span_name, ''), nullIf(ai_events.trace_name, '')), toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')), argMin(ifNull(nullIf(ai_events.span_name, ''), nullIf(ai_events.trace_name, '')), toTimeZone(ai_events.timestamp, 'UTC'))) AS trace_name
+ FROM ai_events
+ WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), equals(ai_events.trace_id, 'trace1'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(ai_events.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'bar'), 0)))
+ GROUP BY ai_events.trace_id
LIMIT 1 SETTINGS readonly=2,
max_execution_time=60,
allow_experimental_object_type=1,
@@ -36,25 +36,25 @@
# ---
# name: TestTraceQueryRunner.test_event_property_filters.1
'''
- SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '') AS id,
- any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_session_id'), ''), 'null'), '^"|"$', '')) AS ai_session_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS first_timestamp,
- max(toTimeZone(events.timestamp, 'UTC')) AS last_timestamp,
- ifNull(nullIf(argMinIf(events.distinct_id, toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$ai_trace')), ''), argMin(events.distinct_id, toTimeZone(events.timestamp, 'UTC'))) AS first_distinct_id,
- round(if(and(equals(countIf(and(ifNull(greater(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), 0), 0), notEquals(events.event, '$ai_generation'))), 0), greater(countIf(and(ifNull(greater(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), 0), 0), equals(events.event, '$ai_generation'))), 0)), sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), and(equals(events.event, '$ai_generation'), ifNull(greater(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), 0), 0))), sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), or(isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_parent_id'), ''), 'null'), '^"|"$', '')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_parent_id'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '')), isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_parent_id'), ''), 'null'), '^"|"$', ''))
- and isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '')))))), 2) AS total_latency,
- nullIf(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_tokens'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS input_tokens,
- nullIf(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_tokens'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS output_tokens,
- nullIf(round(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS input_cost,
- nullIf(round(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS output_cost,
- nullIf(round(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS total_cost,
- arrayDistinct(arraySort(x -> x.3, groupArrayIf(tuple(events.uuid, events.event, toTimeZone(events.timestamp, 'UTC'), events.properties, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_choices'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_state'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_state'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_tools'), ''), 'null'), '^"|"$', '')), notEquals(events.event, '$ai_trace')))) AS events,
- argMinIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_state'), ''), 'null'), '^"|"$', ''), toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$ai_trace')) AS input_state,
- argMinIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_state'), ''), 'null'), '^"|"$', ''), toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$ai_trace')) AS output_state,
- ifNull(argMinIf(ifNull(nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_span_name'), ''), 'null'), '^"|"$', ''), ''), nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_name'), ''), 'null'), '^"|"$', ''), '')), toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$ai_trace')), argMin(ifNull(nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_span_name'), ''), 'null'), '^"|"$', ''), ''), nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_name'), ''), 'null'), '^"|"$', ''), '')), toTimeZone(events.timestamp, 'UTC'))) AS trace_name
- FROM events
- WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', ''), 'trace1'), 0), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'baz'), 0)))
- GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '')
+ SELECT ai_events.trace_id AS id,
+ any(ai_events.session_id) AS ai_session_id,
+ min(toTimeZone(ai_events.timestamp, 'UTC')) AS first_timestamp,
+ max(toTimeZone(ai_events.timestamp, 'UTC')) AS last_timestamp,
+ ifNull(nullIf(argMinIf(ai_events.distinct_id, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')), ''), argMin(ai_events.distinct_id, toTimeZone(ai_events.timestamp, 'UTC'))) AS first_distinct_id,
+ round(if(and(equals(countIf(and(ifNull(greater(ai_events.latency, 0), 0), notEquals(ai_events.event, '$ai_generation'))), 0), greater(countIf(and(ifNull(greater(ai_events.latency, 0), 0), equals(ai_events.event, '$ai_generation'))), 0)), sumIf(ai_events.latency, and(equals(ai_events.event, '$ai_generation'), ifNull(greater(ai_events.latency, 0), 0))), sumIf(ai_events.latency, or(isNull(ai_events.parent_id), ifNull(equals(ai_events.parent_id, ai_events.trace_id), isNull(ai_events.parent_id)
+ and isNull(ai_events.trace_id))))), 2) AS total_latency,
+ nullIf(sumIf(ai_events.input_tokens, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS input_tokens,
+ nullIf(sumIf(ai_events.output_tokens, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS output_tokens,
+ nullIf(round(sumIf(ai_events.input_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS input_cost,
+ nullIf(round(sumIf(ai_events.output_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS output_cost,
+ nullIf(round(sumIf(ai_events.total_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS total_cost,
+ arrayDistinct(arraySort(x -> x.3, groupArrayIf(tuple(ai_events.uuid, ai_events.event, toTimeZone(ai_events.timestamp, 'UTC'), ai_events.properties, ai_events.input, ai_events.output, ai_events.output_choices, ai_events.input_state, ai_events.output_state, ai_events.tools), notEquals(ai_events.event, '$ai_trace')))) AS events,
+ argMinIf(ai_events.input_state, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')) AS input_state,
+ argMinIf(ai_events.output_state, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')) AS output_state,
+ ifNull(argMinIf(ifNull(nullIf(ai_events.span_name, ''), nullIf(ai_events.trace_name, '')), toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')), argMin(ifNull(nullIf(ai_events.span_name, ''), nullIf(ai_events.trace_name, '')), toTimeZone(ai_events.timestamp, 'UTC'))) AS trace_name
+ FROM ai_events
+ WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), equals(ai_events.trace_id, 'trace1'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(ai_events.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'baz'), 0)))
+ GROUP BY ai_events.trace_id
LIMIT 1 SETTINGS readonly=2,
max_execution_time=60,
allow_experimental_object_type=1,
@@ -70,6 +70,41 @@
'''
# ---
# name: TestTraceQueryRunner.test_event_property_filters.2
+ '''
+ SELECT ai_events.trace_id AS id,
+ any(ai_events.session_id) AS ai_session_id,
+ min(toTimeZone(ai_events.timestamp, 'UTC')) AS first_timestamp,
+ max(toTimeZone(ai_events.timestamp, 'UTC')) AS last_timestamp,
+ ifNull(nullIf(argMinIf(ai_events.distinct_id, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')), ''), argMin(ai_events.distinct_id, toTimeZone(ai_events.timestamp, 'UTC'))) AS first_distinct_id,
+ round(if(and(equals(countIf(and(ifNull(greater(ai_events.latency, 0), 0), notEquals(ai_events.event, '$ai_generation'))), 0), greater(countIf(and(ifNull(greater(ai_events.latency, 0), 0), equals(ai_events.event, '$ai_generation'))), 0)), sumIf(ai_events.latency, and(equals(ai_events.event, '$ai_generation'), ifNull(greater(ai_events.latency, 0), 0))), sumIf(ai_events.latency, or(isNull(ai_events.parent_id), ifNull(equals(ai_events.parent_id, ai_events.trace_id), isNull(ai_events.parent_id)
+ and isNull(ai_events.trace_id))))), 2) AS total_latency,
+ nullIf(sumIf(ai_events.input_tokens, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS input_tokens,
+ nullIf(sumIf(ai_events.output_tokens, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS output_tokens,
+ nullIf(round(sumIf(ai_events.input_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS input_cost,
+ nullIf(round(sumIf(ai_events.output_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS output_cost,
+ nullIf(round(sumIf(ai_events.total_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS total_cost,
+ arrayDistinct(arraySort(x -> x.3, groupArrayIf(tuple(ai_events.uuid, ai_events.event, toTimeZone(ai_events.timestamp, 'UTC'), ai_events.properties, ai_events.input, ai_events.output, ai_events.output_choices, ai_events.input_state, ai_events.output_state, ai_events.tools), notEquals(ai_events.event, '$ai_trace')))) AS events,
+ argMinIf(ai_events.input_state, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')) AS input_state,
+ argMinIf(ai_events.output_state, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')) AS output_state,
+ ifNull(argMinIf(ifNull(nullIf(ai_events.span_name, ''), nullIf(ai_events.trace_name, '')), toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')), argMin(ifNull(nullIf(ai_events.span_name, ''), nullIf(ai_events.trace_name, '')), toTimeZone(ai_events.timestamp, 'UTC'))) AS trace_name
+ FROM ai_events
+ WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), equals(ai_events.trace_id, 'trace1'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(ai_events.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'barz'), 0)))
+ GROUP BY ai_events.trace_id
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTraceQueryRunner.test_event_property_filters.3
'''
SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '') AS id,
any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_session_id'), ''), 'null'), '^"|"$', '')) AS ai_session_id,
@@ -106,30 +141,31 @@
# ---
# name: TestTraceQueryRunner.test_person_property_filters
'''
- SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '') AS id,
- any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_session_id'), ''), 'null'), '^"|"$', '')) AS ai_session_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS first_timestamp,
- max(toTimeZone(events.timestamp, 'UTC')) AS last_timestamp,
- ifNull(nullIf(argMinIf(events.distinct_id, toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$ai_trace')), ''), argMin(events.distinct_id, toTimeZone(events.timestamp, 'UTC'))) AS first_distinct_id,
- round(if(and(equals(countIf(and(ifNull(greater(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), 0), 0), notEquals(events.event, '$ai_generation'))), 0), greater(countIf(and(ifNull(greater(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), 0), 0), equals(events.event, '$ai_generation'))), 0)), sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), and(equals(events.event, '$ai_generation'), ifNull(greater(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), 0), 0))), sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_latency'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), or(isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_parent_id'), ''), 'null'), '^"|"$', '')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_parent_id'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '')), isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_parent_id'), ''), 'null'), '^"|"$', ''))
- and isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '')))))), 2) AS total_latency,
- nullIf(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_tokens'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS input_tokens,
- nullIf(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_tokens'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS output_tokens,
- nullIf(round(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS input_cost,
- nullIf(round(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS output_cost,
- nullIf(round(sumIf(accurateCastOrNull(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), 'Float64'), in(events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS total_cost,
- arrayDistinct(arraySort(x -> x.3, groupArrayIf(tuple(events.uuid, events.event, toTimeZone(events.timestamp, 'UTC'), events.properties, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_choices'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_state'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_state'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_tools'), ''), 'null'), '^"|"$', '')), notEquals(events.event, '$ai_trace')))) AS events,
- argMinIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_state'), ''), 'null'), '^"|"$', ''), toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$ai_trace')) AS input_state,
- argMinIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_state'), ''), 'null'), '^"|"$', ''), toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$ai_trace')) AS output_state,
- ifNull(argMinIf(ifNull(nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_span_name'), ''), 'null'), '^"|"$', ''), ''), nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_name'), ''), 'null'), '^"|"$', ''), '')), toTimeZone(events.timestamp, 'UTC'), equals(events.event, '$ai_trace')), argMin(ifNull(nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_span_name'), ''), 'null'), '^"|"$', ''), ''), nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_name'), ''), 'null'), '^"|"$', ''), '')), toTimeZone(events.timestamp, 'UTC'))) AS trace_name
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ SELECT ai_events.trace_id AS id,
+ any(ai_events.session_id) AS ai_session_id,
+ min(toTimeZone(ai_events.timestamp, 'UTC')) AS first_timestamp,
+ max(toTimeZone(ai_events.timestamp, 'UTC')) AS last_timestamp,
+ ifNull(nullIf(argMinIf(ai_events.distinct_id, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')), ''), argMin(ai_events.distinct_id, toTimeZone(ai_events.timestamp, 'UTC'))) AS first_distinct_id,
+ round(if(and(equals(countIf(and(ifNull(greater(ai_events.latency, 0), 0), notEquals(ai_events.event, '$ai_generation'))), 0), greater(countIf(and(ifNull(greater(ai_events.latency, 0), 0), equals(ai_events.event, '$ai_generation'))), 0)), sumIf(ai_events.latency, and(equals(ai_events.event, '$ai_generation'), ifNull(greater(ai_events.latency, 0), 0))), sumIf(ai_events.latency, or(isNull(ai_events.parent_id), ifNull(equals(ai_events.parent_id, ai_events.trace_id), isNull(ai_events.parent_id)
+ and isNull(ai_events.trace_id))))), 2) AS total_latency,
+ nullIf(sumIf(ai_events.input_tokens, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS input_tokens,
+ nullIf(sumIf(ai_events.output_tokens, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS output_tokens,
+ nullIf(round(sumIf(ai_events.input_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS input_cost,
+ nullIf(round(sumIf(ai_events.output_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS output_cost,
+ nullIf(round(sumIf(ai_events.total_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS total_cost,
+ arrayDistinct(arraySort(x -> x.3, groupArrayIf(tuple(ai_events.uuid, ai_events.event, toTimeZone(ai_events.timestamp, 'UTC'), ai_events.properties, ai_events.input, ai_events.output, ai_events.output_choices, ai_events.input_state, ai_events.output_state, ai_events.tools), notEquals(ai_events.event, '$ai_trace')))) AS events,
+ argMinIf(ai_events.input_state, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')) AS input_state,
+ argMinIf(ai_events.output_state, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')) AS output_state,
+ ifNull(argMinIf(ifNull(nullIf(ai_events.span_name, ''), nullIf(ai_events.trace_name, '')), toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')), argMin(ifNull(nullIf(ai_events.span_name, ''), nullIf(ai_events.trace_name, '')), toTimeZone(ai_events.timestamp, 'UTC'))) AS trace_name
+ FROM ai_events
+ INNER JOIN
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS ai_events__pdi___person_id,
+ argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id,
+ person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS ai_events__pdi ON equals(ai_events.distinct_id, ai_events__pdi.distinct_id)
LEFT JOIN
(SELECT person.id AS id,
replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'bar'), ''), 'null'), '^"|"$', '') AS properties___bar
@@ -139,9 +175,9 @@
FROM person
WHERE equals(person.team_id, 99999)
GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
- WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', ''), 'trace1'), 0), ifNull(equals(events__person.properties___bar, 'baz'), 0)))
- GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '')
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS ai_events__pdi__person ON equals(ai_events__pdi.ai_events__pdi___person_id, ai_events__pdi__person.id)
+ WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), equals(ai_events.trace_id, 'trace1'), ifNull(equals(ai_events__pdi__person.properties___bar, 'baz'), 0)))
+ GROUP BY ai_events.trace_id
LIMIT 1 SETTINGS readonly=2,
max_execution_time=60,
allow_experimental_object_type=1,
@@ -157,6 +193,59 @@
'''
# ---
# name: TestTraceQueryRunner.test_person_property_filters.1
+ '''
+ SELECT ai_events.trace_id AS id,
+ any(ai_events.session_id) AS ai_session_id,
+ min(toTimeZone(ai_events.timestamp, 'UTC')) AS first_timestamp,
+ max(toTimeZone(ai_events.timestamp, 'UTC')) AS last_timestamp,
+ ifNull(nullIf(argMinIf(ai_events.distinct_id, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')), ''), argMin(ai_events.distinct_id, toTimeZone(ai_events.timestamp, 'UTC'))) AS first_distinct_id,
+ round(if(and(equals(countIf(and(ifNull(greater(ai_events.latency, 0), 0), notEquals(ai_events.event, '$ai_generation'))), 0), greater(countIf(and(ifNull(greater(ai_events.latency, 0), 0), equals(ai_events.event, '$ai_generation'))), 0)), sumIf(ai_events.latency, and(equals(ai_events.event, '$ai_generation'), ifNull(greater(ai_events.latency, 0), 0))), sumIf(ai_events.latency, or(isNull(ai_events.parent_id), ifNull(equals(ai_events.parent_id, ai_events.trace_id), isNull(ai_events.parent_id)
+ and isNull(ai_events.trace_id))))), 2) AS total_latency,
+ nullIf(sumIf(ai_events.input_tokens, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS input_tokens,
+ nullIf(sumIf(ai_events.output_tokens, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 0) AS output_tokens,
+ nullIf(round(sumIf(ai_events.input_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS input_cost,
+ nullIf(round(sumIf(ai_events.output_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS output_cost,
+ nullIf(round(sumIf(ai_events.total_cost_usd, in(ai_events.event, tuple('$ai_generation', '$ai_embedding'))), 10), 0) AS total_cost,
+ arrayDistinct(arraySort(x -> x.3, groupArrayIf(tuple(ai_events.uuid, ai_events.event, toTimeZone(ai_events.timestamp, 'UTC'), ai_events.properties, ai_events.input, ai_events.output, ai_events.output_choices, ai_events.input_state, ai_events.output_state, ai_events.tools), notEquals(ai_events.event, '$ai_trace')))) AS events,
+ argMinIf(ai_events.input_state, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')) AS input_state,
+ argMinIf(ai_events.output_state, toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')) AS output_state,
+ ifNull(argMinIf(ifNull(nullIf(ai_events.span_name, ''), nullIf(ai_events.trace_name, '')), toTimeZone(ai_events.timestamp, 'UTC'), equals(ai_events.event, '$ai_trace')), argMin(ifNull(nullIf(ai_events.span_name, ''), nullIf(ai_events.trace_name, '')), toTimeZone(ai_events.timestamp, 'UTC'))) AS trace_name
+ FROM ai_events
+ INNER JOIN
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS ai_events__pdi___person_id,
+ argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id,
+ person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS ai_events__pdi ON equals(ai_events.distinct_id, ai_events__pdi.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'bar'), ''), 'null'), '^"|"$', '') AS properties___bar
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS ai_events__pdi__person ON equals(ai_events__pdi.ai_events__pdi___person_id, ai_events__pdi__person.id)
+ WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), equals(ai_events.trace_id, 'trace1'), ifNull(equals(ai_events__pdi__person.properties___bar, 'foo'), 0)))
+ GROUP BY ai_events.trace_id
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTraceQueryRunner.test_person_property_filters.2
'''
SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '') AS id,
any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_session_id'), ''), 'null'), '^"|"$', '')) AS ai_session_id,
diff --git a/posthog/hogql_queries/ai/test/test_ai_table_resolver.py b/posthog/hogql_queries/ai/test/test_ai_table_resolver.py
index 13d4df2144cb..75ff9b44f452 100644
--- a/posthog/hogql_queries/ai/test/test_ai_table_resolver.py
+++ b/posthog/hogql_queries/ai/test/test_ai_table_resolver.py
@@ -1,37 +1,12 @@
+import pytest
from unittest.mock import Mock, patch
from posthog.hogql import ast
-from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback, is_ai_events_enabled
+from posthog.hogql_queries.ai.ai_table_resolver import AIEventsExpiredError, AIEventsNotFoundError, query_ai_events
-class TestIsAiEventsEnabled:
- @patch("posthog.hogql_queries.ai.ai_table_resolver.posthoganalytics.feature_enabled", return_value=True)
- def test_returns_true_when_flag_enabled(self, mock_flag):
- team = Mock(id=123, organization_id="org_abc")
- assert is_ai_events_enabled(team) is True
- mock_flag.assert_called_once_with(
- "ai-events-table-rollout",
- "123",
- groups={"organization": "org_abc"},
- group_properties={"organization": {"id": "org_abc"}},
- send_feature_flag_events=False,
- )
-
- @patch("posthog.hogql_queries.ai.ai_table_resolver.posthoganalytics.feature_enabled", return_value=False)
- def test_returns_false_when_flag_disabled(self, mock_flag):
- team = Mock(id=456, organization_id="org_xyz")
- assert is_ai_events_enabled(team) is False
- mock_flag.assert_called_once_with(
- "ai-events-table-rollout",
- "456",
- groups={"organization": "org_xyz"},
- group_properties={"organization": {"id": "org_xyz"}},
- send_feature_flag_events=False,
- )
-
-
-class TestExecuteWithAiEventsFallback:
+class TestQueryAiEvents:
def _make_query(self):
return ast.SelectQuery(
select=[ast.Field(chain=["trace_id"])],
@@ -43,13 +18,12 @@ class TestExecuteWithAiEventsFallback:
return Mock(results=results)
@patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
- @patch("posthog.hogql_queries.ai.ai_table_resolver.is_ai_events_enabled", return_value=True)
- def test_returns_ai_events_result_when_data_found(self, _mock_flag, mock_execute):
+ def test_returns_ai_events_result_when_data_found(self, mock_execute):
ai_result = self._make_result([["trace-1"]])
mock_execute.return_value = ai_result
team = Mock(id=1, organization_id="org")
- result = execute_with_ai_events_fallback(
+ result = query_ai_events(
query=self._make_query(),
placeholders={},
team=team,
@@ -60,48 +34,59 @@ class TestExecuteWithAiEventsFallback:
assert mock_execute.call_count == 1
@patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
- @patch("posthog.hogql_queries.ai.ai_table_resolver.is_ai_events_enabled", return_value=True)
- def test_falls_back_to_events_when_ai_events_empty(self, _mock_flag, mock_execute):
+ def test_falls_back_to_events_when_ai_events_empty(self, mock_execute):
ai_result = self._make_result([])
events_result = self._make_result([["trace-1"]])
mock_execute.side_effect = [ai_result, events_result]
team = Mock(id=1, organization_id="org")
- result = execute_with_ai_events_fallback(
+ result = query_ai_events(
query=self._make_query(),
placeholders={},
team=team,
query_type="TestQuery",
+ fall_back_to_events=True,
)
assert result is events_result
assert mock_execute.call_count == 2
@patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
- @patch("posthog.hogql_queries.ai.ai_table_resolver.is_ai_events_enabled", return_value=False)
- def test_skips_ai_events_when_kill_switch_off(self, _mock_flag, mock_execute):
- events_result = self._make_result([["trace-1"]])
- mock_execute.return_value = events_result
+ def test_raises_expired_when_ai_events_empty_but_events_has_rows(self, mock_execute):
+ # ai_events empty, events probe finds the row -> the data aged past the TTL.
+ mock_execute.side_effect = [self._make_result([]), self._make_result([[1]])]
team = Mock(id=1, organization_id="org")
- result = execute_with_ai_events_fallback(
- query=self._make_query(),
- placeholders={},
- team=team,
- query_type="TestQuery",
- )
+ with pytest.raises(AIEventsExpiredError):
+ query_ai_events(
+ query=self._make_query(),
+ placeholders={},
+ team=team,
+ query_type="TestQuery",
+ )
+ assert mock_execute.call_count == 2
- assert result is events_result
- assert mock_execute.call_count == 1
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
+ def test_raises_not_found_when_empty_in_both_tables(self, mock_execute):
+ mock_execute.side_effect = [self._make_result([]), self._make_result([])]
+
+ team = Mock(id=1, organization_id="org")
+ with pytest.raises(AIEventsNotFoundError):
+ query_ai_events(
+ query=self._make_query(),
+ placeholders={},
+ team=team,
+ query_type="TestQuery",
+ )
+ assert mock_execute.call_count == 2
@patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
- @patch("posthog.hogql_queries.ai.ai_table_resolver.is_ai_events_enabled", return_value=True)
- def test_rewrites_placeholders_for_ai_events(self, _mock_flag, mock_execute):
+ def test_rewrites_placeholders_for_ai_events(self, mock_execute):
mock_execute.return_value = self._make_result([["found"]])
team = Mock(id=1, organization_id="org")
placeholder = ast.Field(chain=["properties", "$ai_trace_id"])
- execute_with_ai_events_fallback(
+ query_ai_events(
query=self._make_query(),
placeholders={"condition": placeholder},
team=team,
@@ -115,40 +100,40 @@ class TestExecuteWithAiEventsFallback:
assert rewritten.chain == ["trace_id"]
@patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
- @patch("posthog.hogql_queries.ai.ai_table_resolver.is_ai_events_enabled", return_value=False)
- def test_rewrites_placeholders_for_events_fallback(self, _mock_flag, mock_execute):
- mock_execute.return_value = self._make_result([])
+ def test_rewrites_placeholders_for_events_fallback(self, mock_execute):
+ mock_execute.side_effect = [self._make_result([]), self._make_result([["found"]])]
team = Mock(id=1, organization_id="org")
# Use a native ai_events column name in the placeholder
placeholder = ast.Field(chain=["trace_id"])
- execute_with_ai_events_fallback(
+ query_ai_events(
query=self._make_query(),
placeholders={"condition": placeholder},
team=team,
query_type="TestQuery",
+ fall_back_to_events=True,
)
- # The placeholder should have been rewritten from trace_id to properties.$ai_trace_id
+ # The events-table call should rewrite trace_id back to properties.$ai_trace_id
actual_placeholders = mock_execute.call_args.kwargs.get("placeholders", {})
rewritten = actual_placeholders["condition"]
assert isinstance(rewritten, ast.Field)
assert rewritten.chain == ["properties", "$ai_trace_id"]
@patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
- @patch("posthog.hogql_queries.ai.ai_table_resolver.is_ai_events_enabled", return_value=False)
- def test_rewrites_query_from_clause_for_events_fallback(self, _mock_flag, mock_execute):
- mock_execute.return_value = self._make_result([])
+ def test_rewrites_query_from_clause_for_events_fallback(self, mock_execute):
+ mock_execute.side_effect = [self._make_result([]), self._make_result([])]
team = Mock(id=1, organization_id="org")
- execute_with_ai_events_fallback(
+ query_ai_events(
query=self._make_query(),
placeholders={},
team=team,
query_type="TestQuery",
+ fall_back_to_events=True,
)
- # The query's FROM clause should have been rewritten from ai_events to events
+ # The events-table call's FROM clause should have been rewritten to events
actual_query = mock_execute.call_args.kwargs.get("query")
assert isinstance(actual_query, ast.SelectQuery)
assert actual_query.select_from is not None
@@ -156,8 +141,7 @@ class TestExecuteWithAiEventsFallback:
assert actual_query.select_from.table.chain == ["events"]
@patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
- @patch("posthog.hogql_queries.ai.ai_table_resolver.is_ai_events_enabled", return_value=True)
- def test_passes_optional_kwargs(self, _mock_flag, mock_execute):
+ def test_passes_optional_kwargs(self, mock_execute):
mock_execute.return_value = self._make_result([["found"]])
team = Mock(id=1, organization_id="org")
@@ -167,7 +151,7 @@ class TestExecuteWithAiEventsFallback:
settings = Mock()
workload = Mock()
- execute_with_ai_events_fallback(
+ query_ai_events(
query=self._make_query(),
placeholders={},
team=team,
@@ -187,14 +171,13 @@ class TestExecuteWithAiEventsFallback:
assert kwargs["workload"] is workload
@patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
- @patch("posthog.hogql_queries.ai.ai_table_resolver.is_ai_events_enabled", return_value=True)
- def test_omits_unset_optional_kwargs(self, _mock_flag, mock_execute):
+ def test_omits_unset_optional_kwargs(self, mock_execute):
# Unset kwargs must NOT appear in the forwarded call so they don't override
# execute_hogql_query's defaults (workload=DEFAULT, etc).
mock_execute.return_value = self._make_result([["found"]])
team = Mock(id=1, organization_id="org")
- execute_with_ai_events_fallback(
+ query_ai_events(
query=self._make_query(),
placeholders={},
team=team,
diff --git a/posthog/hogql_queries/ai/test/test_trace_query_runner.py b/posthog/hogql_queries/ai/test/test_trace_query_runner.py
index 87e054b714d5..6e44f71d55be 100644
--- a/posthog/hogql_queries/ai/test/test_trace_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_trace_query_runner.py
@@ -6,7 +6,6 @@ from uuid import UUID
import pytest
from freezegun import freeze_time
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, snapshot_clickhouse_queries
-from unittest.mock import patch
from posthog.schema import (
DateRange,
@@ -1491,8 +1490,7 @@ class TestTraceQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertEqual(response.results[0].totalLatency, 300.0)
@freeze_time("2025-01-15T12:00:00Z")
- @patch("posthog.hogql_queries.ai.ai_table_resolver.is_ai_events_enabled", return_value=True)
- def test_fallback_to_events_when_ai_events_empty(self, _mock_flag):
+ def test_fallback_to_events_when_ai_events_empty(self):
"""When ai_events has no data, the fallback to events returns correct results with proper numeric types."""
trace_id = "fallback-test-trace"
_create_person(distinct_ids=["person1"], team=self.team)
diff --git a/posthog/hogql_queries/ai/trace_neighbors_query_runner.py b/posthog/hogql_queries/ai/trace_neighbors_query_runner.py
index 44ed60559945..954484e30549 100644
--- a/posthog/hogql_queries/ai/trace_neighbors_query_runner.py
+++ b/posthog/hogql_queries/ai/trace_neighbors_query_runner.py
@@ -13,7 +13,7 @@ from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.hogql.property import property_to_expr
-from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
@@ -28,11 +28,12 @@ class TraceNeighborsQueryRunner(AnalyticsQueryRunner[TraceNeighborsQueryResponse
cached_response: CachedTraceNeighborsQueryResponse
def _calculate(self):
- result = execute_with_ai_events_fallback(
+ result = query_ai_events(
query=self._build_query(),
placeholders=self._get_placeholders(),
team=self.team,
query_type="TraceNeighborsQuery",
+ fall_back_to_events=True,
timings=self.timings,
modifiers=self.modifiers,
)
diff --git a/posthog/hogql_queries/ai/trace_query_runner.py b/posthog/hogql_queries/ai/trace_query_runner.py
index 5df2aca99ef8..484fb3224c77 100644
--- a/posthog/hogql_queries/ai/trace_query_runner.py
+++ b/posthog/hogql_queries/ai/trace_query_runner.py
@@ -18,7 +18,7 @@ from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.hogql.property import property_to_expr
-from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.hogql_queries.ai.utils import merge_heavy_properties
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
@@ -70,11 +70,12 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):
super().__init__(*args, **kwargs)
def _calculate(self):
- query_result = execute_with_ai_events_fallback(
+ query_result = query_ai_events(
query=self._build_query(),
placeholders={"filter_conditions": self._get_where_clause()},
team=self.team,
query_type=NodeKind.TRACE_QUERY,
+ fall_back_to_events=True,
timings=self.timings,
modifiers=self.modifiers,
limit_context=self.limit_context,
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools_strip_migration.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools_ai_events_routing.py
similarity index 90%
rename from posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools_strip_migration.py
rename to posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools_ai_events_routing.py
index 5032060b0f24..896bf47fc7b1 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools_strip_migration.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools_ai_events_routing.py
@@ -1,4 +1,4 @@
-"""Strip-migration tests for the eval-report agent's heavy-prop tools.
+"""Tests for the eval-report agent's heavy-prop tools.
`sample_generation_details`, `get_generation_detail`, and
`get_generation_text_repr` are the three tools that read heavy columns. They
@@ -50,7 +50,7 @@ def _resolver_response(rows: list[list]) -> MagicMock:
class TestSampleGenerationDetailsRoutesThroughResolver(BaseTest):
- @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events")
@patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
def test_routes_through_resolver_against_ai_events(self, _mock_lookup, mock_resolver):
"""The heavy-prop tool must hit the resolver, not raw `execute_hogql_query`."""
@@ -77,7 +77,7 @@ class TestSampleGenerationDetailsRoutesThroughResolver(BaseTest):
result = _sample_fn(state=_state(self.team.id), generation_ids=[_VALID_GEN_ID])
# Returns rendered JSON with input/output previews from heavy columns.
- assert "post-strip" not in result # sanity: nothing weird leaked
+ assert result
assert mock_resolver.call_count == 1
kwargs = mock_resolver.call_args.kwargs
select = cast(ast.SelectQuery, kwargs["query"])
@@ -90,7 +90,7 @@ class TestSampleGenerationDetailsRoutesThroughResolver(BaseTest):
trace_id_values = [const.value for const in placeholders["trace_ids"].exprs]
assert trace_id_values == ["trace-1"]
- @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events")
@patch(_RESOLVE_PATH, return_value={})
def test_skips_heavy_fetch_when_no_trace_ids_resolved(self, _mock_lookup, mock_resolver):
"""If the events preflight finds no rows (uuids purged or never existed),
@@ -103,7 +103,7 @@ class TestSampleGenerationDetailsRoutesThroughResolver(BaseTest):
class TestGetGenerationDetailRoutesThroughResolver(BaseTest):
- @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events")
@patch("posthog.hogql.query.execute_hogql_query")
@patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
def test_main_query_uses_resolver_eval_query_uses_events(self, _mock_lookup, mock_events, mock_resolver):
@@ -155,7 +155,7 @@ class TestGetGenerationDetailRoutesThroughResolver(BaseTest):
assert "trace_id" in placeholders
assert placeholders["trace_id"].value == "trace-1"
- @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events")
@patch(_RESOLVE_PATH, return_value={})
def test_returns_not_found_when_trace_id_lookup_misses(self, _mock_lookup, mock_resolver):
"""If the events preflight can't find the generation, surface a not-found
@@ -165,7 +165,7 @@ class TestGetGenerationDetailRoutesThroughResolver(BaseTest):
assert mock_resolver.call_count == 0
def test_invalid_generation_id_returns_error_without_querying(self):
- with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:
result = _get_detail_fn(state=_state(self.team.id), generation_id="not-a-uuid")
assert "error" in result.lower()
assert mock_resolver.call_count == 0
@@ -175,9 +175,9 @@ class TestGetGenerationTextReprRoutesThroughResolver(BaseTest):
"""`get_generation_text_repr` reads `$ai_input`/`$ai_output`/`$ai_output_choices`/
`$ai_tools` indirectly through the formatter. Those are 4 of the 6 stripped
heavy columns, so the tool must hit ai_events — querying `events.properties`
- directly would render an empty skeleton post-cutover."""
+ directly would render an empty skeleton (the heavy columns live only on ai_events)."""
- @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events")
@patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
def test_routes_through_resolver_against_ai_events(self, _mock_lookup, mock_resolver):
"""Heavy fetch goes through the resolver and selects from posthog.ai_events."""
@@ -218,7 +218,7 @@ class TestGetGenerationTextReprRoutesThroughResolver(BaseTest):
assert placeholders["trace_id"].value == "trace-1"
assert placeholders["generation_id"].value == _VALID_GEN_ID
- @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events")
@patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
def test_parses_output_choices_dict_format(self, _mock_lookup, mock_resolver):
"""`$ai_output_choices` must arrive as a parsed structure — the formatter's
@@ -245,7 +245,7 @@ class TestGetGenerationTextReprRoutesThroughResolver(BaseTest):
result = _get_text_repr_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID)
assert "choice content" in result
- @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events")
@patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
def test_renders_error_section_when_is_error(self, _mock_lookup, mock_resolver):
"""`is_error` / `error` are dedicated columns — propagate them as
@@ -273,7 +273,7 @@ class TestGetGenerationTextReprRoutesThroughResolver(BaseTest):
assert "ERROR:" in result
assert "boom" in result
- @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events")
@patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
def test_handles_all_heavy_columns_null(self, _mock_lookup, mock_resolver):
"""A generation with all heavy columns nulled should still render — the
@@ -302,7 +302,7 @@ class TestGetGenerationTextReprRoutesThroughResolver(BaseTest):
assert "OUTPUT:" not in result
assert "ERROR:" not in result
- @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events")
@patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
def test_passes_non_json_string_input_through_to_formatter(self, _mock_lookup, mock_resolver):
"""Heavy columns are usually JSON-encoded but a plain text input
@@ -329,7 +329,7 @@ class TestGetGenerationTextReprRoutesThroughResolver(BaseTest):
result = _get_text_repr_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID)
assert "plain text prompt" in result
- @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events")
@patch(_RESOLVE_PATH, return_value={})
def test_returns_not_found_when_trace_id_lookup_misses(self, _mock_lookup, mock_resolver):
"""Skip the heavy fan-out when the events preflight can't find the uuid."""
@@ -337,7 +337,7 @@ class TestGetGenerationTextReprRoutesThroughResolver(BaseTest):
assert "not found" in result.lower()
assert mock_resolver.call_count == 0
- @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events")
@patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
def test_returns_not_found_when_ai_events_query_empty(self, _mock_lookup, mock_resolver):
"""Trace_id resolved but ai_events returns no rows (e.g. raced TTL eviction)."""
@@ -346,7 +346,7 @@ class TestGetGenerationTextReprRoutesThroughResolver(BaseTest):
assert "not found" in result.lower()
def test_invalid_generation_id_returns_error_without_querying(self):
- with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:
with patch(_RESOLVE_PATH) as mock_lookup:
result = _get_text_repr_fn(state=_state(self.team.id), generation_id="not-a-uuid")
assert "error" in result.lower()
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
index 88ee8e419b84..5f2463a9d1b5 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
@@ -75,11 +75,10 @@ def _widened_ts_window(state: dict) -> tuple[datetime, datetime]:
def _execute_hogql(team_id: int, query_str: str, placeholders: dict | None = None) -> list[list]:
"""Execute a HogQL query against `events` and return results.
- Used by every query in this module that does NOT read the six stripped
- heavy columns (`input`, `output`, `output_choices`, `input_state`,
- `output_state`, `tools`). Sweeping these through the resolver too would
- only buy uniform `ai_query_source` tagging — a deliberate scope choice,
- not load-bearing for the strip-heavy migration.
+ Used by every query in this module that does NOT read the six heavy columns
+ (`input`, `output`, `output_choices`, `input_state`, `output_state`, `tools`).
+ Sweeping these through the resolver too would only buy uniform
+ `ai_query_source` tagging — a deliberate scope choice.
"""
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
@@ -105,27 +104,27 @@ def _execute_hogql_via_ai_events(team: "Team", query_str: str, placeholders: dic
"""Execute a HogQL query written against `posthog.ai_events` with the events-table fallback.
Use this only for queries that read heavy columns (`input`, `output`,
- `output_choices`, `input_state`, `output_state`, `tools`) — those are
- stripped from `events.properties` post-cutover and only survive in the
- dedicated `ai_events` table. Other queries should keep using
- `_execute_hogql` against `events`.
+ `output_choices`, `input_state`, `output_state`, `tools`) — those live only
+ on the dedicated `ai_events` table, not in `events.properties`. Other queries
+ should keep using `_execute_hogql` against `events`.
"""
from posthog.hogql.parser import parse_select
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
- from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+ from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
query = parse_select(query_str)
- # `execute_with_ai_events_fallback` sets `product=Product.LLM_ANALYTICS`
+ # `query_ai_events` sets `product=Product.LLM_ANALYTICS`
# internally but not `feature`, so supply it here to keep these eval-report
# agent reads attributed to background enrichment.
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.ENRICHMENT, team_id=team.pk):
- result = execute_with_ai_events_fallback(
+ result = query_ai_events(
query=query,
placeholders=placeholders or {},
team=team,
query_type="EvalReportAgent",
+ fall_back_to_events=True,
)
return result.results or []
@@ -461,8 +460,8 @@ def sample_generation_details(
# $ai_output is empty for chat-format SDK calls (most OpenAI/Anthropic).
# The actual content lives in $ai_output_choices. Use COALESCE to fall back.
# Reads heavy `input` / `output` / `output_choices` / `input_state` /
- # `output_state` — must go through ai_events (post-strip those are NULL on
- # events). On the events fallback the column rewriter rewrites these
+ # `output_state` — must go through ai_events (those live only there as
+ # native columns). On the events fallback the column rewriter rewrites these
# native columns back to `properties.$ai_*`, so the coalesce semantics are
# preserved on both branches.
from posthog.hogql_queries.ai.trace_id_resolver import resolve_trace_ids_for_generation_uuids
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/data.py b/posthog/temporal/ai_observability/evaluation_clustering/data.py
index 9515148a7f8e..895486ec2984 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/data.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/data.py
@@ -28,7 +28,7 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
-from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.hogql_queries.ai.trace_id_resolver import resolve_trace_ids_for_generation_uuids
from posthog.models.team import Team
from posthog.temporal.ai_observability.evaluation_clustering.constants import (
@@ -409,11 +409,11 @@ def fetch_generation_contents(
ids_tuple = ast.Tuple(exprs=[ast.Constant(value=gid) for gid in generation_ids])
trace_ids_tuple = ast.Tuple(exprs=[ast.Constant(value=tid) for tid in trace_ids])
- # Read from `posthog.ai_events` so the heavy `input` / `output_choices`
- # columns survive the strip; the resolver re-runs against the shared
- # `events` table when ai_events returns zero rows (rollout window /
- # kill-switch off). `trace_id IN (...)` gets us the full sorting-key
- # prefix + single-shard reads instead of an N-shard heavy fan-out.
+ # Read the heavy `input` / `output_choices` columns from `posthog.ai_events`,
+ # where they live as native columns; the resolver re-runs against the shared
+ # `events` table when ai_events returns zero rows (data beyond the retention
+ # window). `trace_id IN (...)` gets us the full sorting-key prefix +
+ # single-shard reads instead of an N-shard heavy fan-out.
query = parse_select(
"""
SELECT
@@ -436,11 +436,12 @@ def fetch_generation_contents(
}
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team.id):
- result = execute_with_ai_events_fallback(
+ result = query_ai_events(
query=query,
placeholders=placeholders,
team=team,
query_type="GenerationContentsForLabeling",
+ fall_back_to_events=True,
settings=HogQLGlobalSettings(max_execution_time=CLUSTERING_QUERY_MAX_EXECUTION_TIME),
)
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_strip_migration.py b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_fetch_generation_contents.py
similarity index 84%
rename from posthog/temporal/ai_observability/evaluation_clustering/tests/test_strip_migration.py
rename to posthog/temporal/ai_observability/evaluation_clustering/tests/test_fetch_generation_contents.py
index 8927b02add3e..0f406b61eb49 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_strip_migration.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_fetch_generation_contents.py
@@ -1,4 +1,4 @@
-"""Strip-migration tests for the eval clustering data layer.
+"""Tests for the eval clustering data layer.
`fetch_generation_contents` is the only at-risk reader in
`evaluation_clustering/data.py` (it reads heavy `input` / `output_choices`).
@@ -43,9 +43,7 @@ class TestFetchGenerationContents:
# No queries at all when there's nothing to fetch — guards against
# an N×0 query that would scan the whole window.
with (
- patch(
- "posthog.temporal.ai_observability.evaluation_clustering.data.execute_with_ai_events_fallback"
- ) as mock_resolver,
+ patch("posthog.temporal.ai_observability.evaluation_clustering.data.query_ai_events") as mock_resolver,
patch(_RESOLVE_PATH) as mock_resolve,
):
result = fetch_generation_contents(
@@ -57,9 +55,7 @@ class TestFetchGenerationContents:
@patch(_RESOLVE_PATH, return_value={_GENERATION_ID_1: "trace-A", _GENERATION_ID_2: "trace-B"})
def test_returns_per_generation_dict(self, _mock_resolve, team):
- with patch(
- "posthog.temporal.ai_observability.evaluation_clustering.data.execute_with_ai_events_fallback"
- ) as mock_resolver:
+ with patch("posthog.temporal.ai_observability.evaluation_clustering.data.query_ai_events") as mock_resolver:
# Row tuple: (generation_id, model, input_raw, output_raw)
mock_resolver.return_value = _resolver_response(
[
@@ -91,9 +87,7 @@ class TestFetchGenerationContents:
@patch(_RESOLVE_PATH, return_value={_GENERATION_ID_1: "trace-A"})
def test_truncates_input_and_output(self, _mock_resolve, team):
big = "x" * 5000
- with patch(
- "posthog.temporal.ai_observability.evaluation_clustering.data.execute_with_ai_events_fallback"
- ) as mock_resolver:
+ with patch("posthog.temporal.ai_observability.evaluation_clustering.data.query_ai_events") as mock_resolver:
mock_resolver.return_value = _resolver_response([[_GENERATION_ID_1, "gpt-4o", big, big]])
result = fetch_generation_contents(
team,
@@ -112,12 +106,9 @@ class TestFetchGenerationContents:
@patch(_RESOLVE_PATH, return_value={_GENERATION_ID_1: "trace-A"})
def test_query_reads_native_heavy_columns_from_ai_events(self, _mock_resolve, team):
- """The whole point of the migration is that `input` / `output_choices`
- come off the dedicated `ai_events` columns rather than NULL JSON-extracts
- on `events.properties`. Lock the SQL shape."""
- with patch(
- "posthog.temporal.ai_observability.evaluation_clustering.data.execute_with_ai_events_fallback"
- ) as mock_resolver:
+ """Heavy `input` / `output_choices` come off the dedicated `ai_events`
+ columns, not NULL JSON-extracts on `events.properties`. Lock the SQL shape."""
+ with patch("posthog.temporal.ai_observability.evaluation_clustering.data.query_ai_events") as mock_resolver:
mock_resolver.return_value = _resolver_response([])
fetch_generation_contents(
team, generation_ids=[_GENERATION_ID_1], window_start=_WINDOW_START, window_end=_WINDOW_END
@@ -142,9 +133,7 @@ class TestFetchGenerationContents:
"""The discovered trace_ids must land in the WHERE so the heavy fetch
gets the full ai_events sorting-key prefix + cityHash64 sharding-key
single-shard pruning."""
- with patch(
- "posthog.temporal.ai_observability.evaluation_clustering.data.execute_with_ai_events_fallback"
- ) as mock_resolver:
+ with patch("posthog.temporal.ai_observability.evaluation_clustering.data.query_ai_events") as mock_resolver:
mock_resolver.return_value = _resolver_response([])
fetch_generation_contents(
team,
@@ -162,9 +151,7 @@ class TestFetchGenerationContents:
def test_no_trace_ids_resolved_skips_heavy_fetch(self, _mock_resolve, team):
"""When the events preflight returns nothing — uuids purged or outside
the window — skip the heavy fan-out entirely."""
- with patch(
- "posthog.temporal.ai_observability.evaluation_clustering.data.execute_with_ai_events_fallback"
- ) as mock_resolver:
+ with patch("posthog.temporal.ai_observability.evaluation_clustering.data.query_ai_events") as mock_resolver:
result = fetch_generation_contents(
team, generation_ids=[_GENERATION_ID_1], window_start=_WINDOW_START, window_end=_WINDOW_END
)
@@ -173,9 +160,7 @@ class TestFetchGenerationContents:
@patch(_RESOLVE_PATH, return_value={_GENERATION_ID_1: "trace-A"})
def test_malformed_generation_ids_are_filtered_before_uuid_queries(self, mock_resolve, team):
- with patch(
- "posthog.temporal.ai_observability.evaluation_clustering.data.execute_with_ai_events_fallback"
- ) as mock_resolver:
+ with patch("posthog.temporal.ai_observability.evaluation_clustering.data.query_ai_events") as mock_resolver:
mock_resolver.return_value = _resolver_response([[_GENERATION_ID_1, "gpt-4o", "input", "output"]])
result = fetch_generation_contents(
team,
diff --git a/posthog/temporal/ai_observability/evaluation_event_io.py b/posthog/temporal/ai_observability/evaluation_event_io.py
index a447fc7dfe6e..2abe2825df0f 100644
--- a/posthog/temporal/ai_observability/evaluation_event_io.py
+++ b/posthog/temporal/ai_observability/evaluation_event_io.py
@@ -7,20 +7,16 @@ def extract_event_io(event_type: str, properties: dict[str, Any]) -> tuple[Any,
Returns (input_raw, output_raw) for use in Hog eval globals and preview display.
Invariant: `properties` must already contain the heavy `$ai_*` keys when present
- on the source event. Heavy props are stripped from `events.properties` after the
- cutover (see AI events migration brief), so callers must source the event from a
- path that re-populates them — today that's `EvaluationRunViewSet.create`, which
+ on the source event. Heavy columns live only on the dedicated `ai_events` table —
+ they are not stored in `events.properties` — so callers must source the event from
+ a path that re-populates them. Today that's `EvaluationRunViewSet.create`, which
reads from `ai_events` and re-merges heavy columns via `merge_heavy_properties`
before handing `event_data` to this workflow. Adding a new caller? Use the same
- pattern, or feed it `event_data` produced by an already-migrated reader.
-
- Failure mode this invariant guards against: when `is_ai_events_enabled(team)` is
- False (kill switch flipped) AND the team is post-strip, the events-fallback path
- in `EvaluationRunViewSet.create` returns rows whose `properties` JSON has NULL
- heavy keys. `extract_event_io` would then return empty `input_raw` / `output_raw`,
- and the LLM judge / Hog eval would silently grade an empty conversation. The
- invariant exists so any future caller short-circuiting around the migrated
- reader has to confront this case explicitly.
+ pattern, or feed it `event_data` produced by an already-`ai_events`-backed reader.
+
+ If `properties` arrives without the heavy keys (e.g. sourced from a stripped
+ `events` row), `extract_event_io` returns empty `input_raw` / `output_raw` and the
+ LLM judge / Hog eval would silently grade an empty conversation — hence the invariant.
"""
if event_type == "$ai_generation":
input_raw = properties.get("$ai_input") or properties.get("$ai_input_state", "")
diff --git a/posthog/temporal/ai_observability/sentiment/constants.py b/posthog/temporal/ai_observability/sentiment/constants.py
index 020dd29382bc..5a7faac7a0bd 100644
--- a/posthog/temporal/ai_observability/sentiment/constants.py
+++ b/posthog/temporal/ai_observability/sentiment/constants.py
@@ -55,10 +55,10 @@ BATCH_MAX_GENERATION_IDS = 5 # keep small to avoid upstream request timeouts
# and a size filter to skip accumulated conversation histories — the same
# user messages appear in earlier, smaller generations so we lose nothing.
#
-# Reads from `posthog.ai_events` so post-strip rows still expose the heavy
-# `input` column (it's stripped from `events.properties.$ai_input` after
-# the cutover). `execute_with_ai_events_fallback` rewrites this back to
-# `events.properties.$ai_*` for the shared-table fallback.
+# Reads from `posthog.ai_events`, where the heavy `input` column lives as a
+# native column (it is not stored on `events.properties.$ai_input`).
+# `query_ai_events` rewrites this back to `events.properties.$ai_*` for the
+# retention-window fallback.
GENERATIONS_QUERY = """
SELECT uuid, ai_input, trace_id
FROM (
diff --git a/posthog/temporal/ai_observability/sentiment/data.py b/posthog/temporal/ai_observability/sentiment/data.py
index 2a7f6ce9e4a1..019a4512e548 100644
--- a/posthog/temporal/ai_observability/sentiment/data.py
+++ b/posthog/temporal/ai_observability/sentiment/data.py
@@ -39,13 +39,13 @@ def fetch_generations(
from posthog.hogql.constants import LimitContext
from posthog.hogql.parser import parse_select
- from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+ from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.models.team import Team
team = Team.objects.get(id=team_id)
query = parse_select(GENERATIONS_QUERY)
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team_id):
- result = execute_with_ai_events_fallback(
+ result = query_ai_events(
query=query,
placeholders={
"date_from": ast.Constant(value=date_from),
@@ -56,6 +56,7 @@ def fetch_generations(
},
team=team,
query_type="SentimentOnDemand",
+ fall_back_to_events=True,
limit_context=LimitContext.QUERY_ASYNC,
)
@@ -100,7 +101,7 @@ def fetch_generations_by_uuid(
from posthog.hogql.constants import LimitContext
from posthog.hogql.parser import parse_select
- from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+ from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.hogql_queries.ai.trace_id_resolver import resolve_trace_ids_for_generation_uuids
from posthog.models.team import Team
@@ -125,7 +126,7 @@ def fetch_generations_by_uuid(
query = parse_select(GENERATIONS_BY_UUID_QUERY)
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team_id):
- result = execute_with_ai_events_fallback(
+ result = query_ai_events(
query=query,
placeholders={
"date_from": ast.Constant(value=date_from),
@@ -135,6 +136,7 @@ def fetch_generations_by_uuid(
},
team=team,
query_type="SentimentOnDemandGeneration",
+ fall_back_to_events=True,
limit_context=LimitContext.QUERY_ASYNC,
)
diff --git a/posthog/temporal/ai_observability/sentiment/tests/test_data.py b/posthog/temporal/ai_observability/sentiment/tests/test_data.py
index b146578c5c47..5f223bb8bd29 100644
--- a/posthog/temporal/ai_observability/sentiment/tests/test_data.py
+++ b/posthog/temporal/ai_observability/sentiment/tests/test_data.py
@@ -1,10 +1,8 @@
-"""Strip-migration unit tests for sentiment Temporal data layer.
+"""Unit tests for the sentiment Temporal data layer.
-`fetch_generations` and `fetch_generations_by_uuid` both moved from
-`FROM events SELECT properties.$ai_input` to `FROM posthog.ai_events SELECT input`
-behind the resolver. Both must continue to read populated `ai_input` for
-post-strip events (the resolver wires that up); these tests assert the contract
-without hitting ClickHouse.
+`fetch_generations` and `fetch_generations_by_uuid` read `ai_input` from
+`posthog.ai_events` native columns via `query_ai_events`; these tests assert the
+contract without hitting ClickHouse.
"""
from typing import cast
@@ -36,7 +34,7 @@ def _resolver_response(rows: list[list]) -> MagicMock:
class TestFetchGenerations:
def test_groups_rows_by_trace_id(self, team):
# Each row tuple: (uuid, ai_input, trace_id) — order matches GENERATIONS_QUERY's outer SELECT.
- with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:
mock_resolver.return_value = _resolver_response(
[
["uuid-1", '[{"role":"user","content":"hi A"}]', "trace-A"],
@@ -59,7 +57,7 @@ class TestFetchGenerations:
assert result.total_input_bytes > 0
def test_skips_rows_with_unparseable_input(self, team):
- with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:
mock_resolver.return_value = _resolver_response(
[
["uuid-1", "{not-json", "trace-A"],
@@ -78,7 +76,7 @@ class TestFetchGenerations:
def test_query_reads_native_input_from_ai_events(self, team):
"""If someone reverts the GENERATIONS_QUERY template to
`properties.$ai_input`, this test catches it."""
- with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:
mock_resolver.return_value = _resolver_response([])
fetch_generations(
team_id=team.id,
@@ -103,7 +101,7 @@ _TRACE_RESOLVE_PATH = "posthog.hogql_queries.ai.trace_id_resolver.resolve_trace_
class TestFetchGenerationsByUuid:
@patch(_TRACE_RESOLVE_PATH, return_value={"uuid-1": "trace-A", "uuid-2": "trace-B"})
def test_returns_flat_list(self, _mock_resolve, team):
- with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:
mock_resolver.return_value = _resolver_response(
[
["uuid-1", '[{"role":"user","content":"hi"}]'],
@@ -121,7 +119,7 @@ class TestFetchGenerationsByUuid:
@patch(_TRACE_RESOLVE_PATH, return_value={"uuid-good": "trace-A", "uuid-bad": "trace-A"})
def test_skips_unparseable_input(self, _mock_resolve, team):
- with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:
mock_resolver.return_value = _resolver_response(
[
["uuid-bad", "not-json"],
@@ -141,7 +139,7 @@ class TestFetchGenerationsByUuid:
def test_no_trace_ids_resolved_skips_heavy_fetch(self, _mock_resolve, team):
"""When the events preflight returns no trace_ids — uuids purged or
outside the window — skip the heavy ai_events fan-out entirely."""
- with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:
rows, total_bytes = fetch_generations_by_uuid(
team_id=team.id,
generation_ids=["uuid-1", "uuid-2"],
@@ -157,7 +155,7 @@ class TestFetchGenerationsByUuid:
"""The discovered trace_ids must land in the WHERE so the heavy fetch
hits the ai_events `(team_id, trace_id, timestamp)` sorting-key
prefix and single-shard via the cityHash64 sharding key."""
- with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.query_ai_events") as mock_resolver:
mock_resolver.return_value = _resolver_response([])
fetch_generations_by_uuid(
team_id=team.id,
diff --git a/posthog/temporal/ai_observability/shared_activities.py b/posthog/temporal/ai_observability/shared_activities.py
index dd1c7efac227..15b4ade1d897 100644
--- a/posthog/temporal/ai_observability/shared_activities.py
+++ b/posthog/temporal/ai_observability/shared_activities.py
@@ -22,8 +22,6 @@ async def fetch_all_clustering_filters_activity(
Used by both clustering and summarization coordinators to read
user-configured filters at runtime.
-
- Kept for backward compatibility during rollout.
"""
def _fetch_filters() -> dict[int, list[dict[str, Any]]]:
diff --git a/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py b/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py
index 7f4ceaeeb16d..9335f9ddec21 100644
--- a/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py
+++ b/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py
@@ -9,7 +9,7 @@ from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
-from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.models.team import Team
from posthog.redis import get_async_client
from posthog.sync import database_sync_to_async
@@ -102,9 +102,9 @@ def _fetch_and_format_generation(
end_dt_str = format_datetime_for_clickhouse(window_end)
# Query the dedicated table first; the resolver rewrites + re-runs against the
- # shared `events` table when ai_events returns zero rows. Heavy columns (`input`,
- # `output`) live as native columns on ai_events and as stripped JSON on events
- # post-cutover — only the migrated path can recover them for recent rows.
+ # shared `events` table when ai_events returns zero rows (data beyond the
+ # retention window). Heavy columns (`input`, `output`) live only as native
+ # columns on ai_events, so only this path can recover them for recent rows.
query = parse_select(
"""
SELECT
@@ -126,7 +126,7 @@ def _fetch_and_format_generation(
)
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team.id):
- result = execute_with_ai_events_fallback(
+ result = query_ai_events(
query=query,
placeholders={
"start_dt": ast.Constant(value=start_dt_str),
@@ -136,6 +136,7 @@ def _fetch_and_format_generation(
},
team=team,
query_type="GenerationForSummarization",
+ fall_back_to_events=True,
)
if not result.results:
diff --git a/posthog/temporal/ai_observability/trace_summarization/queries.py b/posthog/temporal/ai_observability/trace_summarization/queries.py
index 23ee89efd99e..39250f51c883 100644
--- a/posthog/temporal/ai_observability/trace_summarization/queries.py
+++ b/posthog/temporal/ai_observability/trace_summarization/queries.py
@@ -1,9 +1,9 @@
"""ClickHouse queries for trace summarization.
Routes through `TraceQueryRunner` so reads land on the dedicated `ai_events`
-table when the rollout flag is on (and fall back to the shared `events` table
-otherwise). The runner re-merges the stripped heavy columns into
-`event.properties`, so downstream formatters keep working post-strip.
+table (falling back to the shared `events` table for data beyond the retention
+window). The runner re-merges the heavy columns into `event.properties`, so
+downstream formatters keep working.
"""
from posthog.schema import DateRange, LLMTrace, NodeKind, TraceQuery
diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py
index 64d347b1393e..3baedeb9dbff 100644
--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py
+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py
@@ -106,7 +106,7 @@ class TestFetchAndFormatActivity:
@pytest.mark.asyncio
async def test_generation_not_found_returns_skipped(self, mock_team):
with patch(
- "posthog.temporal.ai_observability.trace_summarization.fetch_and_format.execute_with_ai_events_fallback"
+ "posthog.temporal.ai_observability.trace_summarization.fetch_and_format.query_ai_events"
) as mock_query:
mock_query.return_value.results = []
@@ -181,7 +181,7 @@ class TestFetchAndFormatActivity:
with (
patch(
- "posthog.temporal.ai_observability.trace_summarization.fetch_and_format.execute_with_ai_events_fallback"
+ "posthog.temporal.ai_observability.trace_summarization.fetch_and_format.query_ai_events"
) as mock_query,
patch("posthog.temporal.ai_observability.trace_summarization.fetch_and_format.get_async_client"),
patch(
diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_strip_migration.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format_heavy_columns.py
similarity index 89%
rename from posthog/temporal/ai_observability/trace_summarization/tests/test_strip_migration.py
rename to posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format_heavy_columns.py
index 7619933e8383..94e07995fff7 100644
--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_strip_migration.py
+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format_heavy_columns.py
@@ -1,8 +1,7 @@
-"""Strip-migration unit tests for the `_fetch_and_format_generation` query.
+"""Unit tests for the `_fetch_and_format_generation` query.
-Verifies the by-uuid generation lookup routes through
-`execute_with_ai_events_fallback` and reads the heavy `input` / `output` from
-`posthog.ai_events` native columns.
+Verifies the by-uuid generation lookup routes through `query_ai_events` and reads
+the heavy `input` / `output` from `posthog.ai_events` native columns.
"""
from typing import cast
@@ -31,10 +30,10 @@ def _resolver_response(rows: list[list]) -> MagicMock:
@pytest.mark.django_db
-class TestFetchAndFormatGenerationStripMigration:
+class TestFetchAndFormatGenerationHeavyColumns:
def test_returns_none_when_resolver_has_no_results(self, team):
with patch(
- "posthog.temporal.ai_observability.trace_summarization.fetch_and_format.execute_with_ai_events_fallback"
+ "posthog.temporal.ai_observability.trace_summarization.fetch_and_format.query_ai_events"
) as mock_resolver:
mock_resolver.return_value = _resolver_response([])
result = _fetch_and_format_generation(
@@ -48,7 +47,7 @@ class TestFetchAndFormatGenerationStripMigration:
def test_returns_text_repr_with_heavy_input_output(self, team):
with patch(
- "posthog.temporal.ai_observability.trace_summarization.fetch_and_format.execute_with_ai_events_fallback"
+ "posthog.temporal.ai_observability.trace_summarization.fetch_and_format.query_ai_events"
) as mock_resolver:
# Order matches SELECT: model, provider, input, output, input_tokens, output_tokens, latency
mock_resolver.return_value = _resolver_response(
@@ -83,9 +82,10 @@ class TestFetchAndFormatGenerationStripMigration:
def test_query_targets_ai_events_with_native_heavy_columns(self, team):
"""If the projection regresses to `properties.$ai_input` / `FROM events`,
- post-strip generation summaries silently empty out. Lock both."""
+ generation summaries silently empty out — the heavy columns live only on
+ `ai_events`. Lock both."""
with patch(
- "posthog.temporal.ai_observability.trace_summarization.fetch_and_format.execute_with_ai_events_fallback"
+ "posthog.temporal.ai_observability.trace_summarization.fetch_and_format.query_ai_events"
) as mock_resolver:
mock_resolver.return_value = _resolver_response([])
diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_queries.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_queries.py
index 4f519b4dd4a9..e563d2b9f471 100644
--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_queries.py
+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_queries.py
@@ -1,8 +1,7 @@
-"""Tests for the migrated `fetch_trace` in the trace-summarization Temporal pipeline.
+"""Tests for `fetch_trace` in the trace-summarization Temporal pipeline.
-Covers the strip-migration contract: heavy columns must come back populated on
-the dedicated path (post-strip rows are only readable there) and the function
-must hand back a fully-formed LLMTrace, not raise.
+Heavy columns must come back populated on the dedicated `ai_events` path (they live
+only there), and the function must hand back a fully-formed LLMTrace, not raise.
"""
import pytest
@@ -61,7 +60,7 @@ class TestFetchTrace:
result = fetch_trace(team, "missing-trace", "2026-04-27T07:00:00+00:00", "2026-04-27T08:00:00+00:00")
assert result is None
- def test_runner_handles_post_strip_heavy_columns(self, team):
+ def test_runner_handles_heavy_columns(self, team):
"""Smoke-checks the contract that the runner's response surfaces heavy
props on the events under `properties.$ai_input`. Real merge logic is
tested in `test_trace_query_runner.py`; here we just assert this
diff --git a/products/ai_observability/AGENTS.md b/products/ai_observability/AGENTS.md
index e12be5999345..3c69ad0ee8b5 100644
--- a/products/ai_observability/AGENTS.md
+++ b/products/ai_observability/AGENTS.md
@@ -30,7 +30,7 @@ single-trace and list reads don't diverge.
## Product docs go under `docs/`
-Rollout plans, migration plans, and product ADRs belong in
+Product ADRs and engineering decision records belong in
`products/ai_observability/docs/`, not at the product root.
## Custom `@action` methods need explicit scope action lists
@@ -74,7 +74,3 @@ forget, the new endpoint silently 403s every API-key caller. The default
test client uses `force_login` and skips the scope check, so unit tests
pass even when the production path is broken. Verify with a personal
API key (or via the MCP layer) before merging.
-
-## See also
-
-- [docs/ai-events-table-rollout.md](./docs/ai-events-table-rollout.md) — ongoing `ai_events` ClickHouse table rollout.
diff --git a/products/ai_observability/README.md b/products/ai_observability/README.md
index d1d33268280b..5e6a7de446a9 100644
--- a/products/ai_observability/README.md
+++ b/products/ai_observability/README.md
@@ -35,7 +35,7 @@ products/ai_observability/
mcp/ # MCP tool definitions
dags/ # Dagster jobs + metrics
skills/ # Agent skills scoped to the product
- docs/ # Product-level docs (rollout plans, ADRs)
+ docs/ # Product-level docs (architecture decision records)
shared/ # Cross-frontend/backend constants, schemas
manifest.tsx # Scene + navigation registration
package.json # Turborepo package (@posthog/products-ai-observability)
@@ -71,5 +71,4 @@ hogli build:openapi
## Further reading
- [AGENTS.md](./AGENTS.md) — product-specific conventions.
-- [docs/ai-events-table-rollout.md](./docs/ai-events-table-rollout.md) — ongoing `ai_events` ClickHouse table rollout.
- [products/architecture.md](../architecture.md) — target architecture for products (facades, contracts, isolation). This product has not yet been migrated.
diff --git a/products/ai_observability/backend/api/evaluation_runs.py b/products/ai_observability/backend/api/evaluation_runs.py
index 26f5061445b7..77f3c9d66f21 100644
--- a/products/ai_observability/backend/api/evaluation_runs.py
+++ b/products/ai_observability/backend/api/evaluation_runs.py
@@ -18,7 +18,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.client import query_with_columns
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.event_usage import report_user_action
-from posthog.hogql_queries.ai.ai_table_resolver import is_ai_events_enabled
+from posthog.hogql_queries.ai.ai_table_resolver import AIEventsExpiredError, AIEventsNotFoundError
from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, HEAVY_COLUMN_TO_PROPERTY, merge_heavy_properties
from posthog.permissions import AccessControlPermission
from posthog.temporal.ai_observability.run_evaluation import RunEvaluationInputs
@@ -106,64 +106,18 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
where_clauses.append("distinct_id = %(distinct_id)s")
params["distinct_id"] = distinct_id
- # Try ai_events first (unless kill switch is off), fall back to events
- query_result: list[dict] = []
- used_ai_events = False
-
- # Tag these direct ClickHouse reads so the manual-eval-trigger lookup is attributed
- # to AI observability in query-usage analysis alongside the rest of the product.
- with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=self.team_id):
- if is_ai_events_enabled(self.team):
- heavy_cols = ",\n ".join(HEAVY_COLUMN_NAMES)
- query_result = query_with_columns(
- f"""
- SELECT
- uuid,
- event,
- properties,
- timestamp,
- team_id,
- distinct_id,
- person_id,
- {heavy_cols}
- FROM ai_events
- WHERE {" AND ".join(where_clauses)}
- LIMIT 1
- """,
- params,
- team_id=self.team_id,
- )
- used_ai_events = len(query_result) > 0
-
- if not query_result:
- query_result = query_with_columns(
- f"""
- SELECT
- uuid,
- event,
- properties,
- timestamp,
- team_id,
- distinct_id,
- person_id
- FROM events
- WHERE {" AND ".join(where_clauses)}
- LIMIT 1
- """,
- params,
- team_id=self.team_id,
- )
-
- if len(query_result) == 0:
+ try:
+ event_data = self._fetch_event_for_evaluation(where_clauses, params)
+ except AIEventsExpiredError:
+ return Response(
+ {
+ "error": f"Event {target_event_id} is past the ai_events retention window and can no longer be evaluated"
+ },
+ status=404,
+ )
+ except AIEventsNotFoundError:
return Response({"error": f"Event {target_event_id} not found"}, status=404)
- event_data = query_result[0]
-
- if used_ai_events:
- # Merge heavy columns back into properties for the evaluation workflow
- heavy_columns = {col: event_data.pop(col, "") for col in HEAVY_COLUMN_TO_PROPERTY}
- event_data["properties"] = merge_heavy_properties(event_data["properties"], heavy_columns)
-
# Build workflow inputs
inputs = RunEvaluationInputs(
evaluation_id=evaluation_id,
@@ -234,3 +188,57 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
error=str(e),
)
return Response({"error": "Failed to start evaluation"}, status=500)
+
+ def _fetch_event_for_evaluation(self, where_clauses: list[str], params: dict[str, object]) -> dict:
+ """Fetch the target event with its heavy AI columns from ai_events.
+
+ An evaluation grades the heavy $ai_input / $ai_output, which live only on the
+ dedicated ai_events table. That table has a retention TTL, so when the event is
+ absent we probe the long-lived events table purely to classify the miss — a
+ stripped events row can't be evaluated either way.
+
+ Raises AIEventsExpiredError if the event is gone from ai_events but still in
+ events (aged past the TTL), or AIEventsNotFoundError if it is in neither.
+ """
+ heavy_cols = ",\n ".join(HEAVY_COLUMN_NAMES)
+ # Tag these direct ClickHouse reads so the manual-eval-trigger lookup is attributed
+ # to AI observability in query-usage analysis alongside the rest of the product.
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=self.team_id):
+ rows = query_with_columns(
+ f"""
+ SELECT
+ uuid,
+ event,
+ properties,
+ timestamp,
+ team_id,
+ distinct_id,
+ person_id,
+ {heavy_cols}
+ FROM ai_events
+ WHERE {" AND ".join(where_clauses)}
+ LIMIT 1
+ """,
+ params,
+ team_id=self.team_id,
+ )
+ if not rows:
+ exists_in_events = query_with_columns(
+ f"""
+ SELECT 1
+ FROM events
+ WHERE {" AND ".join(where_clauses)}
+ LIMIT 1
+ """,
+ params,
+ team_id=self.team_id,
+ )
+ if exists_in_events:
+ raise AIEventsExpiredError("target event has aged past the ai_events retention window")
+ raise AIEventsNotFoundError("target event not found")
+
+ event_data = rows[0]
+ # Merge heavy columns back into properties for the evaluation workflow.
+ heavy_columns = {col: event_data.pop(col, "") for col in HEAVY_COLUMN_TO_PROPERTY}
+ event_data["properties"] = merge_heavy_properties(event_data["properties"], heavy_columns)
+ return event_data
diff --git a/products/ai_observability/backend/api/evaluation_summary.py b/products/ai_observability/backend/api/evaluation_summary.py
index 44225f70263b..0db3f37b6432 100644
--- a/products/ai_observability/backend/api/evaluation_summary.py
+++ b/products/ai_observability/backend/api/evaluation_summary.py
@@ -28,7 +28,7 @@ from posthog.hogql.parser import parse_select
from posthog.api.monitoring import monitor
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.event_usage import report_user_action
-from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.models import Team, User
from posthog.permissions import AccessControlPermission
from posthog.rate_limit import (
@@ -195,7 +195,7 @@ def _fetch_evaluation_runs(
"""
)
- query_result = execute_with_ai_events_fallback(
+ query_result = query_ai_events(
query=query,
placeholders={
"where_clause": ast.And(exprs=where_conditions),
@@ -203,6 +203,7 @@ def _fetch_evaluation_runs(
},
team=team,
query_type="EvaluationSummaryFetchRuns",
+ fall_back_to_events=True,
)
# Transform to expected format
diff --git a/products/ai_observability/backend/api/offline_evaluations.py b/products/ai_observability/backend/api/offline_evaluations.py
index 38a89073d444..87179523d0f4 100644
--- a/products/ai_observability/backend/api/offline_evaluations.py
+++ b/products/ai_observability/backend/api/offline_evaluations.py
@@ -16,7 +16,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.api.monitoring import monitor
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
-from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.permissions import AccessControlPermission
from products.ai_observability.backend.api.metrics import llma_track_latency
@@ -204,7 +204,7 @@ class AIObservabilityOfflineEvaluationsViewSet(TeamAndOrgViewSetMixin, viewsets.
heavy_query = parse_select(_OFFLINE_EXPERIMENT_ITEMS_HEAVY_SQL)
try:
- heavy_result = execute_with_ai_events_fallback(
+ heavy_result = query_ai_events(
query=heavy_query,
placeholders={
"trace_ids": ast.Tuple(exprs=[ast.Constant(value=tid) for tid in trace_ids]),
@@ -213,6 +213,7 @@ class AIObservabilityOfflineEvaluationsViewSet(TeamAndOrgViewSetMixin, viewsets.
},
team=self.team,
query_type="LLMOfflineEvaluationItems",
+ fall_back_to_events=True,
limit_context=LimitContext.QUERY,
)
except Exception as e:
diff --git a/products/ai_observability/backend/api/personal_spend.py b/products/ai_observability/backend/api/personal_spend.py
index 476d756c30fb..9056dd6f8565 100644
--- a/products/ai_observability/backend/api/personal_spend.py
+++ b/products/ai_observability/backend/api/personal_spend.py
@@ -541,7 +541,7 @@ class PersonalSpendViewSet(viewsets.ViewSet):
same scope that covers `/api/users/@me/`). Queries the shared `events`
table directly -- same pattern as the LLM Analytics "Users" tab and every
other person-property filter on AI events. We don't route through
- `execute_with_ai_events_fallback` because the satellite `ai_events`
+ `query_ai_events` because the satellite `ai_events`
cluster's Distributed `person` shim doesn't declare materialized columns
like `pmat_email`, and the helper's fallback only catches empty results,
not the unresolved-identifier exception that would fire there. The
diff --git a/products/ai_observability/backend/api/sentiment.py b/products/ai_observability/backend/api/sentiment.py
index 1411d5468d41..2dfdd3774301 100644
--- a/products/ai_observability/backend/api/sentiment.py
+++ b/products/ai_observability/backend/api/sentiment.py
@@ -34,7 +34,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.api.monitoring import monitor
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
-from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.permissions import AccessControlPermission
from posthog.rate_limit import AIObservabilitySentimentBurstThrottle, AIObservabilitySentimentSustainedThrottle
from posthog.temporal.ai_observability.sentiment.constants import (
@@ -384,11 +384,12 @@ class AIObservabilitySentimentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericVi
"ts_end": ast.Constant(value=ts_end),
}
try:
- heavy_result = execute_with_ai_events_fallback(
+ heavy_result = query_ai_events(
query=heavy_query,
placeholders=heavy_placeholders,
team=self.team,
query_type="LLMSentimentGenerations",
+ fall_back_to_events=True,
limit_context=LimitContext.QUERY,
)
except Exception as e:
diff --git a/products/ai_observability/backend/api/test/test_offline_evaluations.py b/products/ai_observability/backend/api/test/test_offline_evaluations.py
index 5150286cad29..ddb45c8c3a5f 100644
--- a/products/ai_observability/backend/api/test/test_offline_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_offline_evaluations.py
@@ -64,7 +64,7 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
first_seen_at,
]
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
@patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
def test_missing_experiment_id_returns_400(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
response = self.client.post(self.URL, {}, content_type="application/json")
@@ -72,7 +72,7 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
assert mock_preflight.call_count == 0
assert mock_heavy.call_count == 0
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
@patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
def test_empty_experiment_id_returns_400(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
response = self.client.post(self.URL, {"experiment_id": ""}, content_type="application/json")
@@ -80,7 +80,7 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
assert mock_preflight.call_count == 0
assert mock_heavy.call_count == 0
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
@patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
def test_returns_rows_in_20_column_tuple_order(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
mock_preflight.return_value = self._make_response(
@@ -133,7 +133,7 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
assert mock_preflight.call_args.kwargs["query_type"] == "LLMOfflineEvaluationItemsResolve"
assert mock_heavy.call_args.kwargs["query_type"] == "LLMOfflineEvaluationItems"
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
@patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
def test_empty_preflight_skips_heavy_query(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
mock_preflight.return_value = self._make_response([])
@@ -153,7 +153,7 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
("none", None),
]
)
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
@patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
def test_blank_only_trace_ids_short_circuit_heavy(
self, _name: str, blank_value: Any, mock_preflight: MagicMock, mock_heavy: MagicMock
@@ -172,7 +172,7 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
assert body["results"][0][15] is None
assert mock_heavy.call_count == 0
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
@patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
def test_preflight_failure_returns_500(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
mock_preflight.side_effect = RuntimeError("clickhouse boom")
@@ -185,7 +185,7 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
assert mock_heavy.call_count == 0
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
@patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
def test_heavy_failure_returns_500(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
mock_preflight.return_value = self._make_response([self._preflight_row()])
@@ -198,7 +198,7 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
)
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
@patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
def test_preflight_targets_events_and_heavy_targets_ai_events(
self, mock_preflight: MagicMock, mock_heavy: MagicMock
@@ -251,7 +251,7 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
assert heavy_placeholders["ts_start"].value == datetime(2026, 4, 27, 6, 0, tzinfo=UTC)
assert heavy_placeholders["ts_end"].value == datetime(2026, 4, 27, 7, 0, tzinfo=UTC)
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
@patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
def test_traces_without_heavy_match_get_null_input_output(
self, mock_preflight: MagicMock, mock_heavy: MagicMock
@@ -279,7 +279,7 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
assert body["results"][1][14] is None
assert body["results"][1][15] is None
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
@patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
def test_omitted_dates_inline_as_null_guards(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
from posthog.hogql import ast
@@ -307,7 +307,7 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
_BoolCounter().visit(query)
assert len(true_constants) >= 2
- @patch("products.ai_observability.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
@patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
def test_provided_dates_are_inlined_into_query(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
from posthog.hogql import ast
diff --git a/products/ai_observability/backend/api/test/test_sentiment_generations.py b/products/ai_observability/backend/api/test/test_sentiment_generations.py
index 7fb37c4b0e2f..b7562324854d 100644
--- a/products/ai_observability/backend/api/test/test_sentiment_generations.py
+++ b/products/ai_observability/backend/api/test/test_sentiment_generations.py
@@ -31,7 +31,7 @@ class TestSentimentGenerationsEndpoint(APIBaseTest):
) -> list[Any]:
return [uuid, trace_id, model, distinct_id, ts_max, ts_min]
- @patch("products.ai_observability.backend.api.sentiment.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.sentiment.query_ai_events")
@patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")
def test_returns_rows_in_tuple_order(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
mock_preflight.return_value = self._make_response(
@@ -72,7 +72,7 @@ class TestSentimentGenerationsEndpoint(APIBaseTest):
assert mock_preflight.call_args.kwargs["query_type"] == "LLMSentimentGenerationsTraceIdResolve"
assert mock_heavy.call_args.kwargs["query_type"] == "LLMSentimentGenerations"
- @patch("products.ai_observability.backend.api.sentiment.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.sentiment.query_ai_events")
@patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")
def test_invalid_filters_returns_400(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
response = self.client.post(
@@ -90,7 +90,7 @@ class TestSentimentGenerationsEndpoint(APIBaseTest):
("empty_filters_dict", {"filters": {}}),
]
)
- @patch("products.ai_observability.backend.api.sentiment.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.sentiment.query_ai_events")
@patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")
def test_empty_preflight_skips_heavy_query(
self,
@@ -112,7 +112,7 @@ class TestSentimentGenerationsEndpoint(APIBaseTest):
("heavy", "heavy"),
]
)
- @patch("products.ai_observability.backend.api.sentiment.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.sentiment.query_ai_events")
@patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")
def test_clickhouse_failure_returns_500(
self,
@@ -132,7 +132,7 @@ class TestSentimentGenerationsEndpoint(APIBaseTest):
if failing_stage == "preflight":
assert mock_heavy.call_count == 0
- @patch("products.ai_observability.backend.api.sentiment.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.sentiment.query_ai_events")
@patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")
def test_preflight_targets_events_and_heavy_targets_ai_events(
self, mock_preflight: MagicMock, mock_heavy: MagicMock
@@ -188,7 +188,7 @@ class TestSentimentGenerationsEndpoint(APIBaseTest):
# `LimitContext.QUERY`) injects a default of 100 rows and the `GROUP BY
# trace_id` is silently truncated when the preflight returns more, so
# the truncated half renders as blank cards on the Sentiment tab.
- @patch("products.ai_observability.backend.api.sentiment.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.sentiment.query_ai_events")
@patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")
def test_heavy_query_has_explicit_limit(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
from posthog.hogql import ast as hogql_ast
@@ -213,7 +213,7 @@ class TestSentimentGenerationsEndpoint(APIBaseTest):
# the response still includes them positionally. This keeps the
# frontend dedup grouping (and the per-card "View trace" links)
# working for the remaining rows.
- @patch("products.ai_observability.backend.api.sentiment.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.sentiment.query_ai_events")
@patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")
def test_traces_without_heavy_match_get_null_ai_input(
self, mock_preflight: MagicMock, mock_heavy: MagicMock
@@ -266,7 +266,7 @@ class TestSentimentGenerationsRealClickhouse(ClickhouseTestMixin, APIBaseTest):
("with_event", True),
]
)
- @patch("products.ai_observability.backend.api.sentiment.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.api.sentiment.query_ai_events")
def test_preflight_against_real_clickhouse_for_non_utc_team(
self,
_name: str,
diff --git a/products/ai_observability/backend/text_repr/formatters/event_formatter.py b/products/ai_observability/backend/text_repr/formatters/event_formatter.py
index f2c6f2b75649..b84483d74461 100644
--- a/products/ai_observability/backend/text_repr/formatters/event_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/event_formatter.py
@@ -274,7 +274,7 @@ def format_event_text_repr_from_ai_events_row(row: dict[str, Any], options: Form
`properties`-shaped event dict that `format_event_text_repr` consumes.
Use this from query callers that read `posthog.ai_events` directly (i.e.
- that need the heavy columns post-strip-migration). Callers that already
+ that need the heavy columns, which live only there). Callers that already
have an `events.properties` blob should keep using `format_event_text_repr`.
Expected `row` keys: `uuid`, `event`, `timestamp`, plus any of the heavy /
diff --git a/products/ai_observability/backend/tools/run_hog_eval.py b/products/ai_observability/backend/tools/run_hog_eval.py
index a6a74748c011..fa05a934f464 100644
--- a/products/ai_observability/backend/tools/run_hog_eval.py
+++ b/products/ai_observability/backend/tools/run_hog_eval.py
@@ -6,7 +6,7 @@ from posthog.schema import AssistantTool
from posthog.hogql import ast
-from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, merge_heavy_properties
from posthog.sync import database_sync_to_async
@@ -58,10 +58,8 @@ class RunHogEvalTestTool(MaxTool):
team = self._team
# Read from ai_events with native heavy columns so the Hog body still
- # sees `event.properties.$ai_input` etc. for post-strip rows. Falls
- # back to the events table when ai_events returns nothing — only
- # legacy paths still write heavy props into events.properties on the
- # fallback side.
+ # sees `event.properties.$ai_input` etc. Falls back to the events table
+ # when ai_events returns nothing (data beyond the retention window).
query = ast.SelectQuery(
select=[
ast.Field(chain=["uuid"]),
@@ -93,11 +91,12 @@ class RunHogEvalTestTool(MaxTool):
limit=ast.Constant(value=sample_count),
)
- response = await database_sync_to_async(execute_with_ai_events_fallback)(
+ response = await database_sync_to_async(query_ai_events)(
query=query,
placeholders={},
team=team,
query_type="RunHogEvalTest",
+ fall_back_to_events=True,
)
if not response.results:
@@ -109,10 +108,9 @@ class RunHogEvalTestTool(MaxTool):
# Parse all events first to collect property keys and build event data.
# Heavy columns trail the four base columns in row order — re-merge them
# into `properties` so the Hog body can read `properties.$ai_input` etc.
- # On the events fallback the rewriter rewrites the heavy slots back to
- # `properties.$ai_*`, so the merge is *idempotent*: pre-strip rows
- # re-merge values already in `properties`; post-strip rows have NULL
- # heavy slots that `merge_heavy_properties` skips.
+ # `merge_heavy_properties` skips NULL heavy slots, so on the events
+ # fallback (heavy columns absent) it re-merges nothing, and on ai_events
+ # it fills `properties.$ai_*` from the native columns.
parsed_events: list[dict[str, Any]] = []
all_property_keys: set[str] = set()
for row in response.results:
diff --git a/products/ai_observability/backend/tools/test_run_hog_eval.py b/products/ai_observability/backend/tools/test_run_hog_eval.py
index 79976dc650ac..7933e0d5d411 100644
--- a/products/ai_observability/backend/tools/test_run_hog_eval.py
+++ b/products/ai_observability/backend/tools/test_run_hog_eval.py
@@ -52,7 +52,7 @@ class TestRunHogEvalTestTool(BaseTest):
("length_check", "return length(output) > 0;", True),
]
)
- @patch("products.ai_observability.backend.tools.run_hog_eval.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
def test_compilation_and_execution(self, _name, source, expected_verdict, mock_query):
mock_response = MagicMock()
mock_response.results = [_make_event()]
@@ -74,7 +74,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert "Compilation error" in result
assert artifact is None
- @patch("products.ai_observability.backend.tools.run_hog_eval.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
def test_no_events_found(self, mock_query):
mock_response = MagicMock()
mock_response.results = []
@@ -86,7 +86,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert "No recent AI events" in result
assert artifact is None
- @patch("products.ai_observability.backend.tools.run_hog_eval.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
def test_runtime_error_handling(self, mock_query):
mock_response = MagicMock()
mock_response.results = [_make_event()]
@@ -98,7 +98,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert artifact is None
assert "Event" in result
- @patch("products.ai_observability.backend.tools.run_hog_eval.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
def test_result_formatting_includes_previews(self, mock_query):
mock_response = MagicMock()
mock_response.results = [
@@ -116,7 +116,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert "Output:" in result
assert "Result: PASS" in result
- @patch("products.ai_observability.backend.tools.run_hog_eval.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
def test_null_return_shows_na(self, mock_query):
mock_response = MagicMock()
mock_response.results = [_make_event()]
@@ -129,7 +129,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert "N/A" in result
assert "ERROR" not in result
- @patch("products.ai_observability.backend.tools.run_hog_eval.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
def test_runtime_error_shows_error_not_na(self, mock_query):
mock_response = MagicMock()
mock_response.results = [_make_event()]
@@ -142,7 +142,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert "Result: ERROR" in result
assert "Result: N/A" not in result
- @patch("products.ai_observability.backend.tools.run_hog_eval.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
def test_ai_metric_event_type(self, mock_query):
mock_response = MagicMock()
event_row = [
@@ -160,14 +160,13 @@ class TestRunHogEvalTestTool(BaseTest):
assert "PASS" in result
assert "$ai_metric" in result
- @patch("products.ai_observability.backend.tools.run_hog_eval.execute_with_ai_events_fallback")
- def test_heavy_column_remerge_for_stripped_event(self, mock_query):
- """Post-strip rows have empty `properties.$ai_input` on `events`, but
- the dedicated `ai_events` table carries the value in the `input`
+ @patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
+ def test_heavy_column_remerge_from_ai_events(self, mock_query):
+ """On the shared `events` table `properties.$ai_input` is empty, but the
+ dedicated `ai_events` table carries the value in the native `input`
column. The tool must re-merge those native columns back into
- `properties` so the Hog body can read `properties.$ai_input` as
- before. This test simulates the post-strip shape coming back from
- the resolver."""
+ `properties` so the Hog body can read `properties.$ai_input`. This test
+ simulates the ai_events row shape coming back from the resolver."""
from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES
# row[2]: stripped properties (no $ai_input).
@@ -201,7 +200,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert "Result: PASS" in result, f"expected PASS after heavy-merge, got: {result}"
- @patch("products.ai_observability.backend.tools.run_hog_eval.execute_with_ai_events_fallback")
+ @patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
def test_query_targets_ai_events(self, mock_query):
"""The constructed SelectQuery must target `posthog.ai_events` — otherwise
the heavy column slots in the projection are NULL on the events table."""
diff --git a/products/ai_observability/docs/ai-events-table-rollout.md b/products/ai_observability/docs/ai-events-table-rollout.md
deleted file mode 100644
index 614a58409864..000000000000
--- a/products/ai_observability/docs/ai-events-table-rollout.md
+++ /dev/null
@@ -1,141 +0,0 @@
-# ai_events table rollout
-
-## Overview
-
-Dedicated ClickHouse table for AI events with extracted columns
-(trace IDs, tokens, costs, latency, heavy I/O data).
-30-day TTL with partition-level expiration.
-
-## Architecture
-
-- **Write side** (Node.js): `split-ai-events-step.ts`, gated by env vars
-- **Read side** (Python): query runners, gated by `ai-events-table-rollout` feature flag
-- **MV**: populates ai_events from dedicated Kafka topic (`clickhouse_ai_events_json`)
-
-## Env vars
-
-| Var | Default | Purpose |
-| ------------------------------------------------ | ------- | ------------------------------------------------------------------- |
-| `INGESTION_AI_EVENT_SPLITTING_ENABLED` | `false` | Master switch for dual-writing |
-| `INGESTION_AI_EVENT_SPLITTING_TEAMS` | `*` | Always-routed teams (`*` or comma-separated). Unioned with the pct. |
-| `INGESTION_AI_EVENT_SPLITTING_PERCENTAGE` | `0` | Sticky % rollout, deterministic per team_id and monotonic |
-| `INGESTION_AI_EVENT_SPLITTING_STRIP_HEAVY_TEAMS` | `` | Team allowlist for strip-heavy phase (`*` or comma-separated) |
-
-A team is routed to `ai_events` if it's in `_TEAMS` **or** its team_id bucket falls under `_PERCENTAGE`.
-Buckets are stable (Knuth multiplicative hash of `team_id`), so every team in at X% stays in at any
-Y% > X%. `_TEAMS=*` and `_PERCENTAGE=100` are both ways to route everyone.
-
-## Feature flag
-
-`ai-events-table-rollout` -- per team ID, controls read-side table routing.
-
-## Rollout phases
-
-### Phase 1: Deploy code (all gates OFF)
-
-- Feature flag defaults OFF
-- All env vars at defaults (splitting disabled)
-- Zero behavior change from current production
-
-### Phase 2: Enable double-write for test team
-
-```bash
-INGESTION_AI_EVENT_SPLITTING_ENABLED=true
-INGESTION_AI_EVENT_SPLITTING_TEAMS=<llma_team_id>
-INGESTION_AI_EVENT_SPLITTING_STRIP_HEAVY=false # keep heavy props in events
-```
-
-- `events` keeps full data (unchanged)
-- `ai_events` also gets full data
-- Fully reversible: set `ENABLED=false`, zero impact
-
-### Phase 3: Enable reads for test team
-
-- Enable `ai-events-table-rollout` flag for LLMA team ID
-- Query runners + evaluation_runs switch to ai_events
-- Verify: traces page, errors tab, tools tab, evaluation triggers
-- Fully reversible: disable flag -> reads revert to `events` (which has full data)
-
-### Phase 4: CH team backfills last 30 days
-
-- ai_events gets historical data populated
-- Verify: date ranges beyond phase 2 show data correctly
-
-### Phase 5: Expand and flip reads for everyone
-
-- Expand `_PERCENTAGE` 10 → 25 → 50 → 100 to widen the write rollout.
- Each step is a one-line charts PR. Bucketing is sticky per team, so increases only add
- teams, never remove them. Test teams pinned in `_TEAMS` stay routed regardless of the percentage.
-- Expand the read-side feature flag to match.
-- Monitor query latency and data completeness.
-- Once stable: set `_STRIP_HEAVY_TEAMS=*` so events stops getting heavy props.
-- CH team is free to rewrite `events` history to drop heavy columns.
-
-### Phase 6: Cleanup (see section below)
-
-## Rollback at any phase
-
-### Phase 2 rollback (writes only, no stripping)
-
-Set `INGESTION_AI_EVENT_SPLITTING_ENABLED=false`.
-events was never modified -> zero impact.
-
-### Phase 3 rollback (reads enabled, no stripping)
-
-Disable `ai-events-table-rollout` feature flag.
-All reads revert to `events` which has complete data -> zero impact.
-
-### Phase 5 rollback (pre-stripping)
-
-Same as phase 3 -- disable flag, reads revert, events has full data.
-
-### Phase 5 rollback (post-stripping enabled)
-
-1. Disable feature flag -> reads revert to events
-2. Set `STRIP_HEAVY=false` -> new events get full data in events again
-3. Events written during the stripping window have stripped heavy props
- in `events`, but ai_events has full data for those.
- Re-enable the flag if you need to serve that data from ai_events.
-
-### Full rollback from any pre-stripping phase
-
-1. Disable feature flag (instant)
-2. Set `ENABLED=false`
-3. System is back to pre-rollout state, zero data loss
-
-## Code cleanup after GA
-
-After stable GA and CH team has rewritten events history:
-
-### Python read side
-
-- [ ] Remove `is_ai_events_enabled()` from `ai_table_resolver.py`
-- [ ] Remove `posthoganalytics` import from `ai_table_resolver.py`
-- [ ] Remove feature flag guard from `_should_use_ai_events_table()` in all 4 runners
- (method becomes just the TTL check)
-- [ ] Remove events-path from `evaluation_runs.py` (keep only ai_events path)
-- [ ] Extract `_enrich_persons()` from `ai_events_query_runner.py` into a shared utility
- and remove the duplicate from `EventsQueryRunner._calculate()`
-- [ ] Delete feature flag `ai-events-table-rollout` from PostHog
-- [ ] Remove test mocks for `posthoganalytics.feature_enabled`
-
-### Node.js write side
-
-- [ ] Remove `INGESTION_AI_EVENT_SPLITTING_STRIP_HEAVY_TEAMS` env var
- (stripping becomes unconditional, or unnecessary if CH MV strips)
-- [ ] Remove `INGESTION_AI_EVENT_SPLITTING_TEAMS` and `INGESTION_AI_EVENT_SPLITTING_PERCENTAGE` env vars
- (splitting applies to all teams)
-- [ ] Simplify `SplitAiEventsStepConfig` to just `enabled: boolean`
-- [ ] If CH team changes events MV to exclude heavy props at the table level,
- remove stripping logic from `maybeStripAiProperties()` entirely
- (just duplicate unchanged to both outputs)
-
-### Stays permanently
-
-- `AiColumnToPropertyRewriter` -- needed for TTL fallback (queries >30 days)
-- `AiPropertyRewriter` + `AI_PROPERTY_TO_COLUMN` -- needed for HogQL property->column rewriting
-- `merge_heavy_properties()` + `HEAVY_COLUMN_TO_PROPERTY` -- needed by evaluation_runs.py
-- `INGESTION_AI_EVENT_SPLITTING_ENABLED` -- keep as kill switch
-- ai_events table definition, MV, Kafka topic
-- HogQL `AiEventsTable` schema
-- All test utilities (`bulk_create_ai_events`, etc.)
diff --git a/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts b/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts
index c7b825087666..6ddab0faf7e8 100644
--- a/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts
+++ b/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts
@@ -27,7 +27,6 @@ describe('aiObservabilityAIDataLogic', () => {
tools: undefined,
traceId: 'trace-1',
timestamp: '2026-04-30T10:00:00Z',
- aiEventsRolloutEnabled: true,
})
})
.toFinishAllListeners()
@@ -55,8 +54,8 @@ describe('aiObservabilityAIDataLogic', () => {
event: '$ai_generation',
createdAt: '2026-04-30T10:00:00Z',
properties: {
- $ai_input: [{ role: 'user', content: 'post-strip hi' }],
- $ai_output_choices: [{ role: 'assistant', content: 'post-strip hello' }],
+ $ai_input: [{ role: 'user', content: 'hi' }],
+ $ai_output_choices: [{ role: 'assistant', content: 'hello' }],
$ai_tools: [{ function: { name: 'search' } }],
},
},
@@ -82,15 +81,14 @@ describe('aiObservabilityAIDataLogic', () => {
tools: undefined,
traceId: 'trace-1',
timestamp: '2026-04-30T10:00:00Z',
- aiEventsRolloutEnabled: true,
})
})
.toFinishAllListeners()
.toMatchValues({
aiDataCache: {
'event-1': {
- input: [{ role: 'user', content: 'post-strip hi' }],
- output: [{ role: 'assistant', content: 'post-strip hello' }],
+ input: [{ role: 'user', content: 'hi' }],
+ output: [{ role: 'assistant', content: 'hello' }],
tools: [{ function: { name: 'search' } }],
},
},
@@ -113,7 +111,6 @@ describe('aiObservabilityAIDataLogic', () => {
tools: undefined,
traceId: 'trace-1',
timestamp: '2026-04-30T10:00:00Z',
- aiEventsRolloutEnabled: true,
})
})
.toFinishAllListeners()
@@ -144,32 +141,10 @@ describe('aiObservabilityAIDataLogic', () => {
input: undefined,
output: undefined,
tools: undefined,
- aiEventsRolloutEnabled: true,
...coords,
})
}).toFinishAllListeners()
expect(querySpy).not.toHaveBeenCalled()
})
-
- it('skips the fetch when the ai-events-table-rollout flag is off', async () => {
- const querySpy = jest.spyOn(mockApi, 'query')
-
- const logic = aiObservabilityAIDataLogic()
- logic.mount()
-
- await expectLogic(logic, () => {
- logic.actions.loadAIDataForEvent({
- eventId: 'event-1',
- input: undefined,
- output: undefined,
- tools: undefined,
- traceId: 'trace-1',
- timestamp: '2026-04-30T10:00:00Z',
- aiEventsRolloutEnabled: false,
- })
- }).toFinishAllListeners()
-
- expect(querySpy).not.toHaveBeenCalled()
- })
})
diff --git a/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts b/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts
index 1f59cb9dceb0..33bedc150e07 100644
--- a/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts
@@ -21,14 +21,10 @@ export interface LoadAIDataParams {
tools: unknown
traceId?: string
timestamp?: string
- /** True when the team is rolled out to read from `ai_events`. When false, the new path
- * can't help — TraceQuery would just fall back to the shared `events` table, which
- * post-strip-heavy has NULL heavy props. */
- aiEventsRolloutEnabled?: boolean
}
async function loadAIDataAsync(params: LoadAIDataParams): Promise<AIData> {
- const { eventId, input, output, tools, traceId, timestamp, aiEventsRolloutEnabled } = params
+ const { eventId, input, output, tools, traceId, timestamp } = params
// Passthrough: caller already has both sides of the conversation (e.g. the trace page
// hydrates rows from the TraceQuery that has heavy props merged back). No fetch needed.
@@ -42,16 +38,10 @@ async function loadAIDataAsync(params: LoadAIDataParams): Promise<AIData> {
return { input, output, tools }
}
- // The ai_events read path is the only one that can recover heavy props for a stripped
- // event. If the team isn't rolled out, skip the fetch.
- if (!aiEventsRolloutEnabled) {
- return { input, output, tools }
- }
-
- // Post-strip events have NULL heavy props on the shared `events` table. Reuse the
- // existing TraceQuery pipeline (ai_events first, shared `events` on zero rows) to
- // fetch the event's heavy columns by (trace_id, event uuid). TraceQueryDateRange
- // auto-widens the window by ±10 minutes, so a single timestamp is sufficient.
+ // Heavy props live only on `ai_events`. Reuse the existing TraceQuery pipeline
+ // (ai_events first, shared `events` on zero rows) to fetch the event's heavy columns
+ // by (trace_id, event uuid). TraceQueryDateRange auto-widens the window by ±10 minutes,
+ // so a single timestamp is sufficient.
try {
const traceQuery: TraceQuery = {
kind: NodeKind.TraceQuery,
diff --git a/products/ai_observability/frontend/hooks/useAIData.ts b/products/ai_observability/frontend/hooks/useAIData.ts
index 0c4e07dca176..e9eae3116867 100644
--- a/products/ai_observability/frontend/hooks/useAIData.ts
+++ b/products/ai_observability/frontend/hooks/useAIData.ts
@@ -1,8 +1,6 @@
import { useActions, useValues } from 'kea'
import { useEffect } from 'react'
-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-
import { aiObservabilityAIDataLogic } from '../aiObservabilityAIDataLogic'
export interface UseAIDataResult {
@@ -24,7 +22,6 @@ export interface EventData {
export function useAIData(eventData: EventData | undefined): UseAIDataResult {
const { aiDataCache, isEventLoading } = useValues(aiObservabilityAIDataLogic)
const { loadAIDataForEvent } = useActions(aiObservabilityAIDataLogic)
- const aiEventsRolloutEnabled = useFeatureFlag('AI_EVENTS_TABLE_ROLLOUT')
const eventId = eventData?.uuid
const input = eventData?.input
@@ -35,11 +32,9 @@ export function useAIData(eventData: EventData | undefined): UseAIDataResult {
const cached = eventId ? aiDataCache[eventId] : undefined
const loading = eventId ? isEventLoading(eventId) : false
- // Only fire the loader when a real fetch is possible. If we fired it with the flag
- // off (or before flags resolve, when useFeatureFlag returns false), the loader would
- // passthrough and cache `{ input: undefined, output: undefined }` — and once the flag
- // later resolves to true the effect would short-circuit on `cached` and never refetch.
- const canFetch = aiEventsRolloutEnabled && !!traceId && !!timestamp
+ // Only fire the loader when a real fetch is possible — we need trace coordinates to
+ // look the heavy props up via TraceQuery.
+ const canFetch = !!traceId && !!timestamp
useEffect(() => {
if (!eventId || cached || loading || !canFetch) {
@@ -53,21 +48,8 @@ export function useAIData(eventData: EventData | undefined): UseAIDataResult {
tools,
traceId,
timestamp,
- aiEventsRolloutEnabled,
})
- }, [
- cached,
- loading,
- canFetch,
- loadAIDataForEvent,
- eventId,
- input,
- output,
- tools,
- traceId,
- timestamp,
- aiEventsRolloutEnabled,
- ])
+ }, [cached, loading, canFetch, loadAIDataForEvent, eventId, input, output, tools, traceId, timestamp])
if (!eventId) {
return {
@@ -78,8 +60,7 @@ export function useAIData(eventData: EventData | undefined): UseAIDataResult {
}
}
- // When we can't fetch, fall back to whatever was passed in — there's nothing to wait
- // for. Once the flag flips on, the effect re-runs and `cached` takes over.
+ // When we can't fetch, fall back to whatever was passed in — there's nothing to wait for.
return {
input: cached?.input ?? input,
output: cached?.output ?? output,
diff --git a/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts
index 2325bdbd5f40..757b48280103 100644
--- a/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts
+++ b/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts
@@ -165,10 +165,9 @@ interface GenerationsQueryValues {
let lastRawFetchCount = 0
async function fetchGenerations(values: GenerationsQueryValues, cursor: string | null): Promise<SentimentGeneration[]> {
- // Routed through `AIObservabilitySentimentViewSet.generations` which wraps
- // `execute_with_ai_events_fallback`. This keeps the read on the standard
- // kill-switch / fallback / `ai_query_source` tagging contract for the
- // rollout. Response shape is tuple-positional ([uuid, trace_id, ai_input,
+ // Routed through `AIObservabilitySentimentViewSet.generations`, which wraps
+ // `query_ai_events` for consistent `ai_query_source` attribution and the
+ // retention-window fallback. Response shape is tuple-positional ([uuid, trace_id, ai_input,
// model, distinct_id, timestamp, created_at]) — the generated wrapper
// types `results` as `unknown[][]` so the position casts here are
// unavoidable until the response serializer declares per-element types.