:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): prevent React crash on non-string $ai_* event properties (#63234)
Christiaan Hendriksena00b4aff2e83
diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsxindex 3d5655bf4e07..7c5c6885155b 100644--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx@@ -108,6 +108,7 @@ import {formatLLMEventTitle,formatLLMLatency,formatLLMUsage,+ formatModelRowLabel,getEventType,getSessionStartTimestamp,getTraceTimestamp,@@ -1305,24 +1306,15 @@ const TreeNode = React.memo(function TraceNode({})export function renderModelRow(event: LLMTrace | LLMTraceEvent, searchQuery?: string): React.ReactNode | null {- if (isLLMEvent(event)) {- if (event.event === '$ai_generation') {- // if we don't have a span name, we don't want to render the model row as its covered by the event title- if (!event.properties.$ai_span_name) {- return null- }- let model = event.properties.$ai_model- if (event.properties.$ai_provider) {- model = `${model} (${event.properties.$ai_provider})`- }- return searchQuery?.trim() ? (- <SearchHighlight string={model} substring={searchQuery} className="flex-1" />- ) : (- <span className="flex-1 truncate"> {model} </span>- )- }+ const model = formatModelRowLabel(event)+ if (model === null) {+ return null}- return null+ return searchQuery?.trim() ? (+ <SearchHighlight string={model} substring={searchQuery} className="flex-1" />+ ) : (+ <span className="flex-1 truncate"> {model} </span>+ )}function TreeNodeChildren({diff --git a/products/ai_observability/frontend/ConversationDisplay/TagDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/TagDisplay.tsxindex d6f90a538e88..e88bb2cde9d6 100644--- a/products/ai_observability/frontend/ConversationDisplay/TagDisplay.tsx+++ b/products/ai_observability/frontend/ConversationDisplay/TagDisplay.tsx@@ -7,16 +7,17 @@ import { EventType } from '~/types'import { MetadataTag } from '../components/MetadataTag'import { parseTagsCell } from '../generationTagRunsLogic'+import { asString } from '../utils'export function TagDisplay({ eventProperties }: { eventProperties: EventType['properties'] }): JSX.Element {// Reuse the loader's JSON-string defense so a stringified $ai_tags property// doesn't end up iterated character-by-character here.const tags: string[] = parseTagsCell(eventProperties.$ai_tags)- const reasoning = eventProperties.$ai_tag_reasoning- const taggerName = eventProperties.$ai_tagger_name- const model = eventProperties.$ai_model- const traceId = eventProperties.$ai_trace_id- const targetEventId = eventProperties.$ai_target_event_id+ const reasoning = asString(eventProperties.$ai_tag_reasoning)+ const taggerName = asString(eventProperties.$ai_tagger_name)+ const model = asString(eventProperties.$ai_model)+ const traceId = asString(eventProperties.$ai_trace_id)+ const targetEventId = asString(eventProperties.$ai_target_event_id)const tagCount = eventProperties.$ai_tag_countreturn (diff --git a/products/ai_observability/frontend/components/AIObservabilityEventCard.test.tsx b/products/ai_observability/frontend/components/AIObservabilityEventCard.test.tsxnew file mode 100644index 000000000000..591202eb5622--- /dev/null+++ b/products/ai_observability/frontend/components/AIObservabilityEventCard.test.tsx@@ -0,0 +1,55 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import { Provider } from 'kea'++import { initKeaTests } from '~/test/init'++import { AIObservabilityEventCard } from './AIObservabilityEventCard'++describe('AIObservabilityEventCard', () => {+ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ cleanup()+ })++ const renderCard = (event: { event: string; properties: Record<string, unknown> }): HTMLElement => {+ const { container } = render(+ <Provider>+ <AIObservabilityEventCard+ event={{ id: 'event-1', createdAt: '2024-01-01T00:00:00Z', ...event }}+ isExpanded={false}+ onToggleExpand={() => {}}+ />+ </Provider>+ )+ return container+ }++ it('renders a string model for a generation', () => {+ renderCard({ event: '$ai_generation', properties: { $ai_model: 'gpt-4o' } })+ expect(screen.getByText('gpt-4o')).toBeInTheDocument()+ })++ it('renders a string span name for a span', () => {+ renderCard({ event: '$ai_span', properties: { $ai_span_name: 'My Span' } })+ expect(screen.getByText('My Span')).toBeInTheDocument()+ })++ // A non-string `$ai_model`/`$ai_span_name` (the property bag is untyped) must not be rendered+ // verbatim, or React throws error #31 ("Objects are not valid as a React child").+ const nonStringCases: [string, string, Record<string, unknown>, string][] = [+ ['generation with object model', '$ai_generation', { $ai_model: {} }, 'Unknown model'],+ ['generation with array model', '$ai_generation', { $ai_model: [] }, 'Unknown model'],+ ['embedding with object model', '$ai_embedding', { $ai_model: {} }, 'Unknown model'],+ ['span with object span name', '$ai_span', { $ai_span_name: {} }, 'Unnamed span'],+ ]++ it.each(nonStringCases)('renders %s without throwing', (_label, event, properties, expectedFallback) => {+ renderCard({ event, properties })+ expect(screen.getByText(expectedFallback)).toBeInTheDocument()+ })+})diff --git a/products/ai_observability/frontend/components/AIObservabilityEventCard.tsx b/products/ai_observability/frontend/components/AIObservabilityEventCard.tsxindex 79ee05e660f9..3da6b81773d4 100644--- a/products/ai_observability/frontend/components/AIObservabilityEventCard.tsx+++ b/products/ai_observability/frontend/components/AIObservabilityEventCard.tsx@@ -10,7 +10,7 @@ import { EventDetails } from '~/scenes/activity/explore/EventDetails'import { EventType } from '~/types'import { llmGenerationSentimentLazyLoaderLogic } from '../llmGenerationSentimentLazyLoaderLogic'-import { costContextFromProperties, formatLLMCost, hasCostBreakdown } from '../utils'+import { asString, costContextFromProperties, formatLLMCost, hasCostBreakdown } from '../utils'import { CostBreakdownTooltip } from './CostBreakdownTooltip'import { SentimentBar } from './SentimentTag'@@ -49,11 +49,11 @@ export function AIObservabilityEventCard({const hasError = event.properties.$ai_error || event.properties.$ai_is_error// Generation-specific properties- const model = event.properties.$ai_model || 'Unknown model'+ const model = asString(event.properties.$ai_model) || 'Unknown model'const costContext = isGeneration || isEmbedding ? costContextFromProperties(event.properties) : undefined// Span-specific properties- const spanName = event.properties.$ai_span_name || 'Unnamed span'+ const spanName = asString(event.properties.$ai_span_name) || 'Unnamed span'return (<div className="border rounded bg-bg-3000">diff --git a/products/ai_observability/frontend/searchUtils.test.ts b/products/ai_observability/frontend/searchUtils.test.tsindex ce09f3a168e2..51ec8c61524b 100644--- a/products/ai_observability/frontend/searchUtils.test.ts+++ b/products/ai_observability/frontend/searchUtils.test.ts@@ -298,6 +298,26 @@ describe('searchUtils', () => {expect(eventMatchesSearch(event, 'hidden response text')).toBe(true)expect(eventMatchesSearch(event, 'not found anywhere')).toBe(false)})++ // `$ai_span_name`/`$ai_model`/`$ai_provider` are strings by convention, but the event+ // property bag is untyped; a structured value must not crash `.toLowerCase()`.+ it('does not throw when string-by-convention properties are not strings', () => {+ const event = createEvent({+ properties: { $ai_span_name: {}, $ai_model: { oops: true }, $ai_provider: 123 },+ })+ expect(() => eventMatchesSearch(event, 'anything')).not.toThrow()+ // Non-string values are not searchable, but the event name still is+ expect(eventMatchesSearch(event, 'generation')).toBe(true)+ expect(eventMatchesSearch(event, 'oops')).toBe(false)+ })++ it('still matches the string provider when the model is an object', () => {+ const event = createEvent({+ properties: { $ai_span_name: 'Chat', $ai_model: { oops: true }, $ai_provider: 'openai' },+ })+ expect(eventMatchesSearch(event, 'openai')).toBe(true)+ expect(eventMatchesSearch(event, 'claude')).toBe(false)+ })})describe('findSearchOccurrences', () => {@@ -389,16 +409,23 @@ describe('searchUtils', () => {})describe('findSidebarOccurrences', () => {+ const createTraceEvent = (id: string, event: string, properties: Record<string, any>): LLMTraceEvent => ({+ id,+ event,+ properties,+ createdAt: '2024-01-01T00:00:00Z',+ })+it('returns empty array for empty query', () => {- const events = [{ id: 'e1', properties: { $ai_span_name: 'Test' } }]+ const events = [createTraceEvent('e1', '$ai_span', { $ai_span_name: 'Test' })]expect(findSidebarOccurrences(events, '')).toEqual([])expect(findSidebarOccurrences(events, ' ')).toEqual([])})it('finds occurrences in span name', () => {const events = [- { id: 'e1', properties: { $ai_span_name: 'Chat Completion' } },- { id: 'e2', properties: { $ai_span_name: 'Text Generation' } },+ createTraceEvent('e1', '$ai_span', { $ai_span_name: 'Chat Completion' }),+ createTraceEvent('e2', '$ai_span', { $ai_span_name: 'Text Generation' }),]const occurrences = findSidebarOccurrences(events, 'chat')@@ -414,15 +441,11 @@ describe('searchUtils', () => {it('finds occurrences in model and provider', () => {const events = [- {- id: 'e1',- event: '$ai_generation',- properties: {- $ai_span_name: 'Generation',- $ai_model: 'gpt-4',- $ai_provider: 'OpenAI',- },- },+ createTraceEvent('e1', '$ai_generation', {+ $ai_span_name: 'Generation',+ $ai_model: 'gpt-4',+ $ai_provider: 'OpenAI',+ }),]const occurrences = findSidebarOccurrences(events, 'openai')@@ -438,15 +461,11 @@ describe('searchUtils', () => {it('searches in combined model and provider text', () => {const events = [- {- id: 'e1',- event: '$ai_generation',- properties: {- $ai_span_name: 'Gen',- $ai_model: 'claude-3',- $ai_provider: 'Anthropic',- },- },+ createTraceEvent('e1', '$ai_generation', {+ $ai_span_name: 'Gen',+ $ai_model: 'claude-3',+ $ai_provider: 'Anthropic',+ }),]const occurrences = findSidebarOccurrences(events, 'anthropic')@@ -461,34 +480,54 @@ describe('searchUtils', () => {})it('handles events without model or provider', () => {- const events = [- {- id: 'e1',- event: '$ai_generation',- properties: { $ai_span_name: 'Test' },- },- ]+ const events = [createTraceEvent('e1', '$ai_generation', { $ai_span_name: 'Test' })]expect(findSidebarOccurrences(events, 'model')).toEqual([])})it('finds multiple occurrences across events', () => {const events = [- { id: 'e1', properties: { $ai_span_name: 'Test Event' } },- { id: 'e2', properties: { $ai_span_name: 'Another Test' } },- {- id: 'e3',- event: '$ai_generation',- properties: {- $ai_span_name: 'Generation Test',- $ai_model: 'test-model',- },- },+ createTraceEvent('e1', '$ai_span', { $ai_span_name: 'Test Event' }),+ createTraceEvent('e2', '$ai_span', { $ai_span_name: 'Another Test' }),+ createTraceEvent('e3', '$ai_generation', {+ $ai_span_name: 'Generation Test',+ $ai_model: 'test-model',+ }),]const occurrences = findSidebarOccurrences(events, 'test')expect(occurrences).toHaveLength(4)expect(occurrences.map((o) => o.eventId)).toEqual(['e1', 'e2', 'e3', 'e3'])})++ it('matches the rendered model row when the model is not a string', () => {+ const events = [+ createTraceEvent('e1', '$ai_generation', {+ $ai_span_name: 'Chat',+ $ai_model: { oops: true },+ $ai_provider: 'openai',+ }),+ ]+ // The rendered row shows the bare provider, so the occurrence covers exactly that text+ expect(findSidebarOccurrences(events, 'openai')).toEqual([+ {+ type: 'sidebar',+ field: 'model',+ startIndex: 0,+ eventId: 'e1',+ },+ ])+ expect(findSidebarOccurrences(events, 'oops')).toEqual([])+ })++ it('does not throw when span name and model are not strings', () => {+ const events = [+ createTraceEvent('e1', '$ai_generation', {+ $ai_span_name: {},+ $ai_model: { oops: true },+ }),+ ]+ expect(findSidebarOccurrences(events, 'test')).toEqual([])+ })})describe('findMessageOccurrences', () => {diff --git a/products/ai_observability/frontend/searchUtils.ts b/products/ai_observability/frontend/searchUtils.tsindex 1ae3fb45dff1..832011c2d6ac 100644--- a/products/ai_observability/frontend/searchUtils.ts+++ b/products/ai_observability/frontend/searchUtils.ts@@ -1,3 +1,7 @@+import { LLMTraceEvent } from '~/queries/schema/schema-general'++import { asString, formatModelRowLabel } from './utils'+export interface SearchMatch {startIndex: numberlength: number@@ -106,19 +110,19 @@ export function eventMatchesSearch(event: { properties: Record<string, any>; eveconst lowerQuery = query.toLowerCase().trim()// Search in event title- const title = event.properties.$ai_span_name || event.event || ''+ const title = asString(event.properties.$ai_span_name) || event.event || ''if (title.toLowerCase().includes(lowerQuery)) {return true}// Search in model name- const model = event.properties.$ai_model || ''+ const model = asString(event.properties.$ai_model) || ''if (model.toLowerCase().includes(lowerQuery)) {return true}// Search in provider- const provider = event.properties.$ai_provider || ''+ const provider = asString(event.properties.$ai_provider) || ''if (provider.toLowerCase().includes(lowerQuery)) {return true}@@ -207,10 +211,7 @@ export function findTraceOccurrences(/*** Find search occurrences in sidebar event fields (title, model, provider)*/-export function findSidebarOccurrences(- events: Array<{ id: string; event?: string; properties: Record<string, any> }>,- query: string-): SearchOccurrence[] {+export function findSidebarOccurrences(events: LLMTraceEvent[], query: string): SearchOccurrence[] {if (!query.trim()) {return []}@@ -219,7 +220,7 @@ export function findSidebarOccurrences(events.forEach((event) => {// Event title (only from span name, not event.event)- const title = event.properties.$ai_span_name || ''+ const title = asString(event.properties.$ai_span_name) || ''if (title) {occurrences.push(...findSearchOccurrences(title, query, 'title', {@@ -229,21 +230,15 @@ export function findSidebarOccurrences()}- // Model and provider (displayed together in the UI)- if (event.event === '$ai_generation' && event.properties.$ai_span_name) {- let modelText = event.properties.$ai_model || ''- if (event.properties.$ai_provider) {- modelText = `${modelText} (${event.properties.$ai_provider})`- }- // Use 'model' field for the combined model + provider string- if (modelText) {- occurrences.push(- ...findSearchOccurrences(modelText, query, 'model', {- type: 'sidebar',- eventId: event.id,- })- )- }+ // Model and provider, matching the model row rendered in the UI+ const modelText = formatModelRowLabel(event)+ if (modelText) {+ occurrences.push(+ ...findSearchOccurrences(modelText, query, 'model', {+ type: 'sidebar',+ eventId: event.id,+ })+ )}})diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.tsindex 36ddc40225c6..0be49e6a2dcd 100644--- a/products/ai_observability/frontend/utils.test.ts+++ b/products/ai_observability/frontend/utils.test.ts@@ -8,6 +8,7 @@ import {costContextFromTrace,formatAiErrorForDisplay,formatLLMEventTitle,+ formatModelRowLabel,getInternalTagName,getSessionID,getSessionStartTimestamp,@@ -1598,6 +1599,105 @@ describe.each(IMPLS)('AI observability utils [$name]', ({ normalizeMessage, normexpect(formatLLMEventTitle(event)).toBe('Custom Action')})})++ describe('non-string properties (untyped property bag)', () => {+ // `$ai_*` title properties are strings by convention, but the event property bag is+ // untyped. A structured value (object/array) or number must never be returned verbatim,+ // or it would be rendered as a raw React child and crash the page (React error #31).+ const cases: Array<[string, string, Record<string, unknown>, string]> = [+ [+ 'generation, object span name, with model',+ '$ai_generation',+ { $ai_span_name: {}, $ai_model: 'gpt-4' },+ 'gpt-4',+ ],+ ['generation, object span name, no model', '$ai_generation', { $ai_span_name: {} }, 'Generation'],+ ['generation, object model', '$ai_generation', { $ai_model: {} }, 'Generation'],+ [+ 'generation, object model, with provider',+ '$ai_generation',+ { $ai_model: {}, $ai_provider: 'openai' },+ 'Generation (openai)',+ ],+ ['generation, object provider', '$ai_generation', { $ai_model: 'gpt-4', $ai_provider: {} }, 'gpt-4'],+ ['embedding, object span name', '$ai_embedding', { $ai_span_name: {} }, 'Embedding'],+ ['embedding, object model', '$ai_embedding', { $ai_model: {} }, 'Embedding'],+ ['span, object span name', '$ai_span', { $ai_span_name: {} }, 'Span'],+ ['span, array span name', '$ai_span', { $ai_span_name: [] }, 'Span'],+ ['span, numeric span name', '$ai_span', { $ai_span_name: 123 }, 'Span'],+ ]++ it.each(cases)('%s falls back to a string label', (_label, event, properties, expected) => {+ const traceEvent: LLMTraceEvent = {+ id: 'event-1',+ event,+ properties,+ createdAt: '2024-01-01T00:00:00Z',+ }+ const title = formatLLMEventTitle(traceEvent)+ expect(typeof title).toBe('string')+ expect(title).toBe(expected)+ })+ })+ })++ describe('formatModelRowLabel', () => {+ it('returns null for a trace', () => {+ const trace: LLMTrace = {+ id: 'trace-1',+ createdAt: '2024-01-01T00:00:00Z',+ distinctId: 'user-1',+ person: {+ uuid: 'person-1',+ created_at: '2024-01-01T00:00:00Z',+ properties: {},+ distinct_id: 'user-1',+ },+ events: [],+ }+ expect(formatModelRowLabel(trace)).toBeNull()+ })++ const cases: Array<[string, string, Record<string, unknown>, string | null]> = [+ // Only generations with a span name get a model row; otherwise the event title covers it.+ ['span event', '$ai_span', { $ai_span_name: 'My Span', $ai_model: 'gpt-4' }, null],+ ['embedding event', '$ai_embedding', { $ai_span_name: 'Embed', $ai_model: 'gpt-4' }, null],+ ['generation without span name', '$ai_generation', { $ai_model: 'gpt-4' }, null],+ ['generation with object span name', '$ai_generation', { $ai_span_name: {}, $ai_model: 'gpt-4' }, null],+ [+ 'generation with model and provider',+ '$ai_generation',+ { $ai_span_name: 'Chat', $ai_model: 'gpt-4', $ai_provider: 'openai' },+ 'gpt-4 (openai)',+ ],+ ['generation with model only', '$ai_generation', { $ai_span_name: 'Chat', $ai_model: 'gpt-4' }, 'gpt-4'],+ [+ 'generation with object model and string provider',+ '$ai_generation',+ { $ai_span_name: 'Chat', $ai_model: {}, $ai_provider: 'openai' },+ 'openai',+ ],+ [+ 'generation with string model and object provider',+ '$ai_generation',+ { $ai_span_name: 'Chat', $ai_model: 'gpt-4', $ai_provider: {} },+ 'gpt-4',+ ],+ ['generation with object model only', '$ai_generation', { $ai_span_name: 'Chat', $ai_model: {} }, null],+ ['generation with array model only', '$ai_generation', { $ai_span_name: 'Chat', $ai_model: [] }, null],+ ['generation with numeric model only', '$ai_generation', { $ai_span_name: 'Chat', $ai_model: 4 }, null],+ ['generation without model or provider', '$ai_generation', { $ai_span_name: 'Chat' }, null],+ ]++ it.each(cases)('%s', (_label, event, properties, expected) => {+ const traceEvent: LLMTraceEvent = {+ id: 'event-1',+ event,+ properties,+ createdAt: '2024-01-01T00:00:00Z',+ }+ expect(formatModelRowLabel(traceEvent)).toBe(expected)+ })})describe('LiteLLM support', () => {diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.tsindex 9e835ca70d65..aee46b28efe7 100644--- a/products/ai_observability/frontend/utils.ts+++ b/products/ai_observability/frontend/utils.ts@@ -924,38 +924,48 @@ export function getSessionStartTimestamp(timestamp: string): string {export function formatLLMEventTitle(event: LLMTrace | LLMTraceEvent): string {if (isLLMEvent(event)) {+ const spanName = asString(event.properties.$ai_span_name)+if (event.event === '$ai_generation') {- const spanName = event.properties.$ai_span_nameif (spanName) {- return `${spanName}`- }- const title = event.properties.$ai_model || 'Generation'- if (event.properties.$ai_provider) {- return `${title} (${event.properties.$ai_provider})`+ return spanName}-- return title+ const title = asString(event.properties.$ai_model) || 'Generation'+ const provider = asString(event.properties.$ai_provider)+ return provider ? `${title} (${provider})` : title}if (event.event === '$ai_embedding') {- const spanName = event.properties.$ai_span_nameif (spanName) {- return `${spanName}`+ return spanName}- const title = event.properties.$ai_model || 'Embedding'- if (event.properties.$ai_provider) {- return `${title} (${event.properties.$ai_provider})`- }-- return title+ const title = asString(event.properties.$ai_model) || 'Embedding'+ const provider = asString(event.properties.$ai_provider)+ return provider ? `${title} (${provider})` : title}- return event.properties.$ai_span_name ?? 'Span'+ return spanName ?? 'Span'}return event.traceName ?? 'Trace'}+export function formatModelRowLabel(event: LLMTrace | LLMTraceEvent): string | null {+ if (!isLLMEvent(event) || event.event !== '$ai_generation') {+ return null+ }+ // if we don't have a span name, we don't want to render the model row as its covered by the event title+ if (!asString(event.properties.$ai_span_name)) {+ return null+ }+ const model = asString(event.properties.$ai_model)+ const provider = asString(event.properties.$ai_provider)+ if (model && provider) {+ return `${model} (${provider})`+ }+ return model || provider || null+}+/*** Lightweight XML-ish content detector for UI toggles.* - NOTE: Scans only the first 2KB for signals (to avoid performance issues with regex)