: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): export large traces without exceeding the string length cap (#82709)
Carlos Marchald35c8ddd14d8
diff --git a/products/ai_observability/frontend/traceExportUtils.test.ts b/products/ai_observability/frontend/traceExportUtils.test.tsindex ce17f8991aba..3df96c093aaa 100644--- a/products/ai_observability/frontend/traceExportUtils.test.ts+++ b/products/ai_observability/frontend/traceExportUtils.test.ts@@ -1,7 +1,7 @@import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'import { EnrichedTraceTreeNode } from './aiObservabilityTraceDataLogic'-import { buildMinimalTraceJSON } from './traceExportUtils'+import { buildMinimalTraceJSON, buildTraceJSONFragments } from './traceExportUtils'describe('traceExportUtils', () => {const mockTrace: LLMTrace = {@@ -486,4 +486,47 @@ describe('traceExportUtils', () => {])})})++ describe('buildTraceJSONFragments', () => {+ const leaf = (event: LLMTraceEvent, children?: EnrichedTraceTreeNode[]): EnrichedTraceTreeNode => ({+ event,+ children,+ displayTotalCost: 0,+ displayLatency: 0,+ displayUsage: null,+ attachedFeedback: [],+ })++ const trees: [string, EnrichedTraceTreeNode[]][] = [+ ['no events', []],+ ['a single event', [leaf(mockSpanEvent)]],+ ['sibling events', [leaf(mockSpanEvent), leaf(mockGenerationEvent), leaf(mockErrorEvent)]],+ ['nested children', [leaf(mockSpanEvent, [leaf(mockGenerationEvent), leaf(mockErrorEvent)])]],+ ['several levels of nesting', [leaf(mockSpanEvent, [leaf(mockSpanEvent, [leaf(mockGenerationEvent)])])]],+ [+ 'siblings and nesting combined',+ [+ leaf(mockSpanEvent, [leaf(mockGenerationEvent), leaf(mockSpanEvent, [leaf(mockErrorEvent)])]),+ leaf(mockGenerationEvent),+ ],+ ],+ ]++ test.each(trees)('joined fragments parse back to the same trace for %s', (_name, tree) => {+ const fragments = buildTraceJSONFragments(mockTrace, tree)++ expect(JSON.parse(fragments.join(''))).toEqual(+ JSON.parse(JSON.stringify(buildMinimalTraceJSON(mockTrace, tree)))+ )+ })++ it('keeps every fragment smaller than the whole trace', () => {+ const tree = [leaf(mockSpanEvent, [leaf(mockGenerationEvent), leaf(mockErrorEvent)])]++ const fragments = buildTraceJSONFragments(mockTrace, tree)++ const longestFragment = Math.max(...fragments.map((fragment) => fragment.length))+ expect(longestFragment).toBeLessThan(JSON.stringify(buildMinimalTraceJSON(mockTrace, tree)).length)+ })+ })})diff --git a/products/ai_observability/frontend/traceExportUtils.ts b/products/ai_observability/frontend/traceExportUtils.tsindex 916c8192e569..6e0ae1ca9621 100644--- a/products/ai_observability/frontend/traceExportUtils.ts+++ b/products/ai_observability/frontend/traceExportUtils.ts@@ -1,3 +1,5 @@+import { lemonToast } from '@posthog/lemon-ui'+import { copyToClipboard } from 'lib/utils/copyToClipboard'import { downloadFile } from 'lib/utils/dom'import { slugify } from 'lib/utils/strings'@@ -162,12 +164,55 @@ function buildTraceJSONString(trace: LLMTrace, tree: EnrichedTraceTreeNode[]): sreturn JSON.stringify(buildMinimalTraceJSON(trace, tree), null, 2)}+function pushEventFragments(event: MinimalEventExport, fragments: string[]): void {+ const { children, ...eventWithoutChildren } = event+ if (!children?.length) {+ fragments.push(JSON.stringify(event))+ return+ }+ // Drop the closing brace so the children array can be streamed into the same object.+ fragments.push(`${JSON.stringify(eventWithoutChildren).slice(0, -1)},"children":[`)+ children.forEach((child, index) => {+ if (index > 0) {+ fragments.push(',')+ }+ pushEventFragments(child, fragments)+ })+ fragments.push(']}')+}++/**+ * Serializes a trace as JSON fragments, one per event, instead of a single string.+ * A large trace exceeds V8's maximum string length, which `JSON.stringify` cannot+ * produce at all. `Blob` concatenates the fragments natively, so only each event+ * has to fit in a string.+ */+export function buildTraceJSONFragments(trace: LLMTrace, tree: EnrichedTraceTreeNode[]): string[] {+ const { events, ...traceMetadata } = buildMinimalTraceJSON(trace, tree)+ const fragments = [`${JSON.stringify(traceMetadata).slice(0, -1)},"events":[`]+ events.forEach((event, index) => {+ if (index > 0) {+ fragments.push(',')+ }+ pushEventFragments(event, fragments)+ })+ fragments.push(']}')+ return fragments+}+export async function exportTraceToClipboard(trace: LLMTrace, tree: EnrichedTraceTreeNode[]): Promise<void> {- await copyToClipboard(buildTraceJSONString(trace, tree), 'trace data')+ let traceJSON: string+ try {+ traceJSON = buildTraceJSONString(trace, tree)+ } catch {+ lemonToast.error('This trace is too large to copy. Use "Download file" instead.')+ return+ }+ await copyToClipboard(traceJSON, 'trace data')}export function exportTraceToFile(trace: LLMTrace, tree: EnrichedTraceTreeNode[]): void {const filename = `${slugify(trace.id || 'trace')}.trace.json`- const file = new File([buildTraceJSONString(trace, tree)], filename, { type: 'application/json' })+ const file = new File(buildTraceJSONFragments(trace, tree), filename, { type: 'application/json' })downloadFile(file)}