: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(aiobs): close parser gaps found by sampling prod payloads (#61136)
Carlos Marchale05df62ec493
diff --git a/products/ai_observability/frontend/normalizer/coverageHarness.test.ts b/products/ai_observability/frontend/normalizer/coverageHarness.test.tsnew file mode 100644index 000000000000..35c0c07664d7--- /dev/null+++ b/products/ai_observability/frontend/normalizer/coverageHarness.test.ts@@ -0,0 +1,194 @@+// Empirical coverage harness: runs the legacy normalizer and the recipe-based+// `RecipeNormalizer` over a sample of REAL production payloads and reports where+// they diverge. This is how the known divergences in `../utils.test.ts` were+// found, and how to re-validate after changing a recipe.+//+// It is gated on the sample files existing, so it SKIPS in CI and in a normal+// `jest` run — it only does work when you've pulled a fresh sample locally.+//+// ── Reproducing ────────────────────────────────────────────────────────────+// 1. Authenticate (opens SSO in your browser, once per region):+// hogli metabase:login --region us+// hogli metabase:login --region eu+// 2. Find the ClickHouse data-tier DB id for each region:+// hogli metabase:databases --region us # e.g. "PostHog ClickHouse PROD US ONLINE"+// hogli metabase:databases --region eu # e.g. "PostHog ClickHouse PROD EU Data Tier"+// 3. Sample uniformly by team (so high-volume teams don't dominate) into the+// directory this harness reads (default /tmp/parser-coverage):+// hogli metabase:query --region us --database-id <ID> --save /tmp/parser-coverage/sample-us.tsv <<'SQL'+// SELECT team_id, toString(uuid) AS event_uuid, provider, model, input, output_choices+// FROM ai_events+// WHERE event = '$ai_generation'+// AND timestamp > now() - INTERVAL 6 HOUR+// AND cityHash64(toString(uuid)) % 500 = 0 -- ~0.2% prefilter, keeps the sort in memory+// AND (input != '' OR output_choices != '')+// LIMIT 3 BY team_id -- uniform: at most 3 events per team+// LIMIT 20000+// SETTINGS max_execution_time = 120+// SQL+// (repeat with --region eu and --save .../sample-eu.tsv)+// 4. Run this harness:+// RECIPE_COVERAGE_DIR=/tmp/parser-coverage pnpm --filter @posthog/frontend jest --testPathPattern=coverageHarness+// It writes <dir>/report.md (bucketed divergences) and logs a one-line summary.+//+// NEVER commit the sample TSVs or the report — they contain raw customer payloads.++import { existsSync, readFileSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'++import type { CompatMessage } from '../types'+import * as legacy from '../utils'+import { RecipeNormalizer } from './index'++const DIR = process.env.RECIPE_COVERAGE_DIR ?? '/tmp/parser-coverage'+const REGIONS = ['us', 'eu'] as const+const samplePath = (region: string): string => join(DIR, `sample-${region}.tsv`)+const haveSamples = REGIONS.some((r) => existsSync(samplePath(r)))++interface Sample {+ region: string+ teamId: number+ eventUuid: string+ provider: string+ column: 'input' | 'output_choices'+ raw: string+}++function loadSamples(region: string): Sample[] {+ if (!existsSync(samplePath(region))) {+ return []+ }+ const lines = readFileSync(samplePath(region), 'utf8').split('\n').filter(Boolean)+ const header = lines[0].split('\t')+ const at = (cells: string[], name: string): string => cells[header.indexOf(name)]+ const out: Sample[] = []+ for (const line of lines.slice(1)) {+ const cells = line.split('\t')+ for (const column of ['input', 'output_choices'] as const) {+ const raw = at(cells, column)+ if (raw && raw !== '' && raw !== '\\N') {+ out.push({+ region,+ teamId: Number(at(cells, 'team_id')),+ eventUuid: at(cells, 'event_uuid'),+ provider: at(cells, 'provider'),+ column,+ raw,+ })+ }+ }+ }+ return out+}++// Order-insensitive deep equality, matching Jest's `toEqual`: object key order+// is not a behavioral difference, but array (message) order is. Treats a missing+// key and an explicit `undefined` as equal.+function deepEqual(a: unknown, b: unknown): boolean {+ if (a === b) {+ return true+ }+ if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') {+ return false+ }+ if (Array.isArray(a) || Array.isArray(b)) {+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => deepEqual(x, b[i]))+ }+ const ao = a as Record<string, unknown>+ const bo = b as Record<string, unknown>+ const keys = (o: Record<string, unknown>): string[] => Object.keys(o).filter((k) => o[k] !== undefined)+ const ak = keys(ao)+ return ak.length === keys(bo).length && ak.every((k) => k in bo && deepEqual(ao[k], bo[k]))+}++// A coarse structural fingerprint so divergences with the same shape group together.+function signature(value: unknown, depth = 0): string {+ if (depth > 3) {+ return '…'+ }+ if (value === null) {+ return 'null'+ }+ if (Array.isArray(value)) {+ const uniq = [...new Set(value.slice(0, 5).map((v) => signature(v, depth + 1)))]+ return uniq.length === 1 ? `[${uniq[0]}*${value.length}]` : `[${uniq.join('|')}]`+ }+ if (typeof value === 'object') {+ const obj = value as Record<string, unknown>+ const tags = ['type', 'role']+ .filter((k) => k in obj)+ .map((k) => `${k}=${JSON.stringify(obj[k])}`)+ .join(',')+ const keys = Object.keys(obj).sort().join(',')+ return tags ? `{${keys}|${tags}}` : `{${keys}}`+ }+ return typeof value+}++const describeOrSkip = haveSamples ? describe : describe.skip++describeOrSkip('recipe coverage vs legacy (empirical)', () => {+ it('reports divergences over sampled production payloads', () => {+ const recipe = new RecipeNormalizer()+ const samples = REGIONS.flatMap(loadSamples)++ let match = 0+ const buckets = new Map<string, { count: number; example: Sample; legacy: string; recipe: string }>()++ for (const s of samples) {+ let parsed: unknown+ try {+ parsed = JSON.parse(s.raw)+ } catch {+ continue+ }+ const role = s.column === 'input' ? 'user' : 'assistant'+ const run = (fn: () => CompatMessage[]): CompatMessage[] | { error: string } => {+ try {+ return fn()+ } catch (err) {+ return { error: err instanceof Error ? err.message : String(err) }+ }+ }+ const a = run(() => legacy.normalizeMessages(parsed, role))+ const b = run(() => recipe.normalizeMessages(parsed, role))+ if (deepEqual(a, b)) {+ match+++ continue+ }+ const sig = signature(parsed)+ const existing = buckets.get(sig)+ if (existing) {+ existing.count+++ } else {+ buckets.set(sig, { count: 1, example: s, legacy: JSON.stringify(a), recipe: JSON.stringify(b) })+ }+ }++ const diverge = samples.length - match+ const lines = [+ `# Recipe coverage vs legacy`,+ '',+ `- samples: ${samples.length} across ${new Set(samples.map((s) => s.teamId)).size} teams`,+ `- match: ${match} (${((match / samples.length) * 100).toFixed(1)}%)`,+ `- diverge: ${diverge} (${((diverge / samples.length) * 100).toFixed(1)}%)`,+ '',+ '## Divergences by shape',+ '',+ ]+ for (const [sig, info] of [...buckets].sort((x, y) => y[1].count - x[1].count)) {+ lines.push(`### ${info.count}× \`${sig}\``)+ lines.push(+ `- example: team ${info.example.teamId} (${info.example.region}), \`${info.example.provider}\`, ${info.example.column}, uuid \`${info.example.eventUuid}\``+ )+ lines.push(`- legacy: \`${info.legacy.slice(0, 300).replace(/`/g, "'")}\``)+ lines.push(`- recipe: \`${info.recipe.slice(0, 300).replace(/`/g, "'")}\``)+ lines.push('')+ }+ writeFileSync(join(DIR, 'report.md'), lines.join('\n'))+ // eslint-disable-next-line no-console+ console.warn(+ `[coverage] ${samples.length} samples · ${match} match · ${diverge} diverge · report → ${join(DIR, 'report.md')}`+ )+ }, 120000)+})diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/select.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/select.tsindex 04b56dddcc0e..c3497fcde5a5 100644--- a/products/ai_observability/frontend/normalizer/recipe/ast/expr/select.ts+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/select.ts@@ -18,7 +18,10 @@ export class SelectExpr extends FilterExpr {return this.onNotArray(scope)}const filtered = this.where ? arr.filter((item) => this.where!.matches(item)) : arr- const result = this.pluck ? filtered.map((item) => this.pluck!.eval(scope.withInput(item))) : filtered+ let result: unknown[] = filtered+ if (this.pluck) {+ result = filtered.map((item) => this.pluck!.eval(scope.withInput(item))).filter((v) => v != null)+ }return this.withIfEmpty(result, scope)}}diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.ts b/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.tsindex f7dc51b7c9c7..f82905bdf1e3 100644--- a/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.ts+++ b/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.ts@@ -16,7 +16,7 @@ export abstract class Rule {const messages: CompatMessage[] = []for (const followup of this.followups) {if (followup.kind === 'static') {- const msg = engine.coercer.buildMessage(followup.emit, scope)+ const msg = engine.coercer.buildMessage(followup.emit, scope, /* allowDrop */ true)if (msg) {messages.push(msg)}diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/anthropic.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/anthropic.yamlindex 63519a61fd18..3f0e39a7a449 100644--- a/products/ai_observability/frontend/normalizer/recipe/default_recipes/anthropic.yaml+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/anthropic.yaml@@ -82,7 +82,6 @@ rules:where: { type: tool_use }followups:- role: $.role- content: ''toolCalls: $.tool_calls- on:diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/langchain_envelope.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/langchain_envelope.yamlnew file mode 100644index 000000000000..9be69b3a3b1e--- /dev/null+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/langchain_envelope.yaml@@ -0,0 +1,12 @@+# LangChain `lc_serializable` envelope ({lc, type: constructor, kwargs}). The real+# message is in `kwargs`; delegate it so the bare langchain rule picks it up.++id: langchain_envelope+priority: 15++rules:+ - on:+ lc: 1+ type: constructor+ kwargs: { is: object }+ delegate: $.kwargsdiff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/typed_agent_items.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/typed_agent_items.yamlnew file mode 100644index 000000000000..6bb0ca6103c8--- /dev/null+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/typed_agent_items.yaml@@ -0,0 +1,30 @@+# Flat type-discriminated agent-item stream (OpenAI Agents SDK and similar):+# {type: message, role, content}, {type: tool_call, callId, name, arguments},+# {type: tool_result, callId, name, output}. Items arrive as array elements that+# the dispatcher flattens, so each is matched here on its own. Without these,+# tool_call / tool_result items match nothing and fall to cajole's stringify.++id: typed_agent_items+priority: 42++rules:+ - on:+ type: tool_call+ callId: { is: string }+ name: { is: string }+ emit:+ role: assistant+ content: ''+ toolCall:+ id: $.callId+ name: $.name+ args: $.arguments++ - on:+ type: tool_result+ callId: { is: string }+ emit:+ role: tool+ content:+ stringify: $.output+ toolCallId: $.callIddiff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/wrappers.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/wrappers.yamlnew file mode 100644index 000000000000..8bcbfebe5556--- /dev/null+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/wrappers.yaml@@ -0,0 +1,32 @@+# Single-field content wrappers (`{content}` / `{message}` / `{text}`, no role+# or type). Legacy lost the text to its stringify fallback; these salvage it.+# Role is left to the default (the column's role) rather than forced to `user`,+# so an output-side wrapper stays `assistant`.++id: wrappers+priority: 90++rules:+ - on:+ role: { exists: false }+ type: { exists: false }+ content: { is: string }+ emit:+ content: $.content++ - on:+ role: { exists: false }+ type: { exists: false }+ content: { exists: false }+ message: { is: string }+ emit:+ content: $.message++ - on:+ role: { exists: false }+ type: { exists: false }+ content: { exists: false }+ message: { exists: false }+ text: { is: string }+ emit:+ content: $.textdiff --git a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.tsindex edfc3ff9b529..5d323d35e9f2 100644--- a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts+++ b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts@@ -32,7 +32,13 @@ export class RecipeNormalizer {// `tools` is a function parameter, not a message shape, so it has no recipe.messages.push({ role: AVAILABLE_TOOLS_ROLE, content: '', tools })}- messages.push(...this.normalizeMessage(input, defaultRole))+ if (carriesMessages(input)) {+ messages.push(...this.normalizeMessage(input, defaultRole))+ }return messages}}++function carriesMessages(input: unknown): boolean {+ return Array.isArray(input) || typeof input === 'string' || (typeof input === 'object' && input !== null)+}diff --git a/products/ai_observability/frontend/normalizer/recipe/registry.ts b/products/ai_observability/frontend/normalizer/recipe/registry.tsindex e4d332cbb8e6..e0920c7e6a0a 100644--- a/products/ai_observability/frontend/normalizer/recipe/registry.ts+++ b/products/ai_observability/frontend/normalizer/recipe/registry.ts@@ -6,11 +6,14 @@ import cajole from './default_recipes/cajole.yaml?raw'import compatArray from './default_recipes/compat_array.yaml?raw'import dispatcherEntry from './default_recipes/dispatcher_entry.yaml?raw'import langchain from './default_recipes/langchain.yaml?raw'+import langchainEnvelope from './default_recipes/langchain_envelope.yaml?raw'import litellm from './default_recipes/litellm.yaml?raw'import openaiChat from './default_recipes/openai_chat.yaml?raw'import openaiResponses from './default_recipes/openai_responses.yaml?raw'import otel from './default_recipes/otel.yaml?raw'+import typedAgentItems from './default_recipes/typed_agent_items.yaml?raw'import vercelSdk from './default_recipes/vercel_sdk.yaml?raw'+import wrappers from './default_recipes/wrappers.yaml?raw'import { Recipe } from './spec/recipe'const RECIPE_SOURCES = {@@ -19,11 +22,14 @@ const RECIPE_SOURCES = {compatArray,dispatcherEntry,langchain,+ langchainEnvelope,litellm,openaiChat,openaiResponses,otel,+ typedAgentItems,vercelSdk,+ wrappers,}const RECIPES: Recipe[] = Object.entries(RECIPE_SOURCES).map(([name, source]) => {diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.tsindex 317ed75b7d88..dc89a9910d52 100644--- a/products/ai_observability/frontend/utils.test.ts+++ b/products/ai_observability/frontend/utils.test.ts@@ -44,7 +44,7 @@ const IMPLS = [},] as const-describe.each(IMPLS)('AI observability utils [$name]', ({ normalizeMessage, normalizeMessages }) => {+describe.each(IMPLS)('AI observability utils [$name]', ({ name, normalizeMessage, normalizeMessages }) => {beforeEach(() => {console.warn = jest.fn()})@@ -2744,4 +2744,170 @@ describe.each(IMPLS)('AI observability utils [$name]', ({ normalizeMessage, normexpect(getToolNamesCalled(events)).toEqual([])})})++ // Regressions found by sampling real production payloads across teams (see+ // normalizer/coverageHarness.test.ts). These shapes were mishandled by the+ // recipe pipeline; both implementations must agree on them.+ describe('production payload regressions', () => {+ it('null input carries no message', () => {+ // Recipe used to salvage `null` into a spurious empty user message.+ expect(normalizeMessages(null, 'user')).toEqual([])+ })++ it('number/boolean input carries no message', () => {+ expect(normalizeMessages(42, 'user')).toEqual([])+ expect(normalizeMessages(true, 'user')).toEqual([])+ })++ it('a single-field {content} object inherits the default role', () => {+ // Recipe used to force role:user even on the output (assistant) side.+ expect(normalizeMessages({ content: 'hi' }, 'assistant')).toEqual([{ role: 'assistant', content: 'hi' }])+ expect(normalizeMessages({ content: 'hi' }, 'user')).toEqual([{ role: 'user', content: 'hi' }])+ })++ it('an empty top-level tool_calls array adds no synthetic message', () => {+ // Recipe used to append an empty assistant message for `tool_calls: []`.+ // (thinking+text content so the Anthropic envelope path is exercised.)+ const message = {+ role: 'assistant',+ content: [+ { type: 'thinking', thinking: 'x' },+ { type: 'text', text: 'done' },+ ],+ tool_calls: [],+ }+ expect(normalizeMessage(message, 'assistant')).toEqual([+ { role: 'assistant (thinking)', content: 'x' },+ { role: 'assistant', content: 'done' },+ ])+ })++ it('OTel parts whose text lives under an unexpected key degrade to empty content, not [null]', () => {+ // `text`-keyed parts (some SDKs) don't match the `content` pluck; the+ // result must collapse to '' rather than a malformed [null] array.+ const message = { role: 'user', parts: [{ type: 'text', text: 'hi' }] }+ expect(normalizeMessage(message, 'user')).toEqual([{ role: 'user', content: '' }])+ })+ })++ // Cases where the recipe pipeline deliberately IMPROVES on legacy. The legacy+ // path retires once the recipe pipeline is the default, at which point these+ // collapse to a single assertion. Until then each documents both behaviors.+ describe('accepted divergences (recipe improvements)', () => {+ const expectByImpl = (input: unknown, role: string, legacyOut: unknown, recipeOut: unknown): void => {+ expect(normalizeMessages(input, role)).toEqual(name === 'recipe' ? recipeOut : legacyOut)+ }++ it('extracts single-field {text}/{message} wrappers instead of stringifying them', () => {+ // legacy stringifies the whole object; recipe surfaces the inner text.+ expectByImpl(+ { text: 'hello' },+ 'assistant',+ [{ role: 'assistant', content: '{"text":"hello"}' }],+ [{ role: 'assistant', content: 'hello' }]+ )+ })++ it('empties null content instead of preserving it', () => {+ // legacy keeps content:null (and the empty tool_calls); recipe+ // normalizes content to '' (renderers expect a string) and drops the+ // empty tool_calls.+ expectByImpl(+ { role: 'assistant', content: null, tool_calls: [] },+ 'assistant',+ [{ role: 'assistant', content: null, tool_calls: [] }],+ [{ role: 'assistant', content: '' }]+ )+ })++ it('preserves and canonicalizes a tool_call that legacy drops', () => {+ // The tool_call lacks the `type: "function"` marker, so legacy's+ // strict guard rejects the whole array and loses the call. Recipe+ // canonicalizes it to {type, id, function:{name, parsed args}}.+ const input = {+ role: 'assistant',+ content: null,+ tool_calls: [+ {+ id: 'call_1',+ caller: { type: 'direct' },+ index: 0,+ function: { name: 'send_email', arguments: '{"to":"[email protected]"}' },+ },+ ],+ }+ expectByImpl(+ input,+ 'assistant',+ [{ role: 'assistant', content: null }],+ [+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ type: 'function',+ id: 'call_1',+ function: { name: 'send_email', arguments: { to: '[email protected]' } },+ },+ ],+ },+ ]+ )+ })++ it('flattens a doubly-nested message array instead of stringifying it', () => {+ // legacy stringifies the inner array as one user message; recipe flattens.+ const input = [+ [+ { role: 'system', content: 'a' },+ { role: 'user', content: 'b' },+ ],+ ]+ expectByImpl(+ input,+ 'user',+ [{ role: 'user', content: '[{"role":"system","content":"a"},{"role":"user","content":"b"}]' }],+ [+ { role: 'system', content: 'a' },+ { role: 'user', content: 'b' },+ ]+ )+ })++ it('parses typed agent items (tool_call/tool_result) legacy stringifies or drops', () => {+ // Flat type-discriminated agent stream (OpenAI Agents SDK and similar).+ // legacy stringifies the tool_call and drops the tool_result's output;+ // recipe produces a real tool call and tool message.+ const input = [+ { type: 'tool_call', callId: 'c1', name: 'getWeather', arguments: { city: 'NYC' } },+ { type: 'tool_result', callId: 'c1', name: 'getWeather', output: { tempF: 71 } },+ ]+ expectByImpl(+ input,+ 'user',+ [+ {+ role: 'user',+ content: '{"type":"tool_call","callId":"c1","name":"getWeather","arguments":{"city":"NYC"}}',+ },+ { role: 'assistant (tool result)' },+ ],+ [+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ type: 'function',+ id: 'c1',+ function: { name: 'getWeather', arguments: { city: 'NYC' } },+ },+ ],+ },+ { role: 'tool', content: '{"tempF":71}', tool_call_id: 'c1' },+ ]+ )+ })+ })})