: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): summarize session traces by ID instead of posting them (#79091)
posthog[bot]5416a2051853
diff --git a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.test.ts b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.test.tsindex 265490ddaa05..debbfd749def 100644--- a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.test.ts+++ b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.test.ts@@ -6,6 +6,16 @@ import { initKeaTests } from '~/test/init'import { aiObservabilitySessionDataLogic } from './aiObservabilitySessionDataLogic'import { aiObservabilitySessionLogic } from './aiObservabilitySessionLogic'+import { llmAnalyticsSummarizationBatchCheckCreate, llmAnalyticsSummarizationCreate } from './generated/api'++jest.mock('./generated/api', () => ({+ ...jest.requireActual('./generated/api'),+ llmAnalyticsSummarizationBatchCheckCreate: jest.fn(),+ llmAnalyticsSummarizationCreate: jest.fn(),+}))++const batchCheckCreate = llmAnalyticsSummarizationBatchCheckCreate as jest.Mock+const summarizationCreate = llmAnalyticsSummarizationCreate as jest.Mockdescribe('aiObservabilitySessionDataLogic', () => {let sessionLogic: ReturnType<typeof aiObservabilitySessionLogic.build>@@ -39,6 +49,9 @@ describe('aiObservabilitySessionDataLogic', () => {beforeEach(() => {initKeaTests()+ batchCheckCreate.mockReset()+ batchCheckCreate.mockResolvedValue({ summaries: [] })+ summarizationCreate.mockReset()querySpy = jest.spyOn(api, 'query').mockResolvedValue(sessionResponse([traceWithEvents()]))sessionLogic = aiObservabilitySessionLogic()sessionLogic.mount()@@ -134,4 +147,21 @@ describe('aiObservabilitySessionDataLogic', () => {expect(logic.values.expandedGenerationIds).toEqual(new Set(['first-event']))})++ it('summarizes a trace by ID instead of posting its contents', async () => {+ summarizationCreate.mockResolvedValue({ summary: { title: 'A short title' }, text_repr: '' })+ logic.actions.loadFullTraceSuccess('trace-1', traceWithEvents(), '-7d\0')++ logic.actions.summarizeTrace('trace-1', false)+ await settleListeners()++ expect(summarizationCreate.mock.calls[0][1]).toEqual({+ mode: 'minimal',+ force_refresh: false,+ trace_id: 'trace-1',+ date_from: '2025-12-31T00:00:00.000Z',+ date_to: '2026-01-02T00:00:00.000Z',+ })+ expect(logic.values.traceSummaries['trace-1'].title).toBe('A short title')+ })})diff --git a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.tsindex c961cbecac2c..612946464c45 100644--- a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts+++ b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts@@ -33,10 +33,9 @@ import type {TraceSpansQueryResponse,} from '../../../frontend/src/queries/schema/schema-general'import { aiObservabilitySessionLogic } from './aiObservabilitySessionLogic'-import { restoreTree } from './aiObservabilityTraceDataLogic'import { SessionTurn, extractSessionTurns } from './extractSessionTurns'-import { llmAnalyticsSummarizationBatchCheckCreate } from './generated/api'-import { eventLabel } from './utils'+import { llmAnalyticsSummarizationBatchCheckCreate, llmAnalyticsSummarizationCreate } from './generated/api'+import { eventLabel, getSummarizationLookupDateRange } from './utils'export interface TraceSummary {title: string@@ -562,35 +561,15 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLog}try {- // If a trace is missing from the session response, fetch it directly as a fallback.- let fullTrace: LLMTrace | undefined = values.fullTraces[traceId]- if (!fullTrace) {- const dateRange = getTraceQueryDateRange(values.dateRange)- const traceQuery: TraceQuery = {- kind: NodeKind.TraceQuery,- traceId,- dateRange,- }- const traceResponse = await api.query(traceQuery)- if (traceResponse.results && traceResponse.results[0]) {- fullTrace = traceResponse.results[0]- } else {- throw new Error('Failed to load full trace')- }- }-- // Build the hierarchy tree from full trace events- const hierarchy = restoreTree(fullTrace.events || [], traceId)-- // nosemgrep: prefer-codegen-api- const data = await api.create(`api/environments/${teamId}/llm_analytics/summarization/`, {- summarize_type: 'trace',+ // Summarize by ID. The backend refetches the trace, so we neither load it here+ // just to post it straight back, nor risk a body big enough for the proxy to+ // reject with a 413.+ const trace = values.fullTraces[traceId] ?? values.traces.find((t) => t.id === traceId)+ const data = await llmAnalyticsSummarizationCreate(String(teamId), {mode: 'minimal',force_refresh: forceRefresh,- data: {- trace: fullTrace,- hierarchy,- },+ trace_id: traceId,+ ...getSummarizationLookupDateRange(trace?.createdAt),})actions.summarizeTraceSuccess(traceId, data.summary?.title || 'Untitled trace')diff --git a/products/ai_observability/frontend/summary-view/summaryViewLogic.ts b/products/ai_observability/frontend/summary-view/summaryViewLogic.tsindex 717b01831749..ebab4bdf4ef0 100644--- a/products/ai_observability/frontend/summary-view/summaryViewLogic.ts+++ b/products/ai_observability/frontend/summary-view/summaryViewLogic.ts@@ -2,7 +2,6 @@ import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path,import { loaders } from 'kea-loaders'import { ApiError, isTransientServerError } from 'lib/api-error'-import { dayjs } from 'lib/dayjs'import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'import { teamLogic } from 'scenes/teamLogic'@@ -11,6 +10,7 @@ import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'import { EnrichedTraceTreeNode } from '../aiObservabilityTraceDataLogic'import { llmAnalyticsSummarizationCreate } from '../generated/api'import type { StructuredSummaryApi, SummarizeRequestApi, SummarizeResponseApi } from '../generated/api.schemas'+import { getSummarizationLookupDateRange } from '../utils'export type SummaryMode = NonNullable<SummarizeRequestApi['mode']>@@ -104,21 +104,6 @@ export type summaryViewLogicType = MakeLogicType<summaryViewLogicMeta>-/**- * Days either side of the entity's own timestamp to search for it, instead of the endpoint's 30-day- * default. Narrow keeps the lookup off traces that reuse a customer-supplied ID, and a single trace- * rarely spans longer than this.- */-const LOOKUP_WINDOW_DAYS = 1--function lookupWindow(createdAt: string): Pick<SummarizeRequestApi, 'date_from' | 'date_to'> {- const timestamp = dayjs(createdAt)- return {- date_from: timestamp.subtract(LOOKUP_WINDOW_DAYS, 'day').toISOString(),- date_to: timestamp.add(LOOKUP_WINDOW_DAYS, 'day').toISOString(),- }-}-const GENERIC_SUMMARY_ERROR = "Couldn't generate a summary. Try again, and if it keeps happening contact support."function bodylessStatusMessage(error: ApiError): string {@@ -258,7 +243,7 @@ export const summaryViewLogic = kea<summaryViewLogicType>([mode,force_refresh: forceRefresh,...(props.trace ? { trace_id: entity.id } : { generation_id: entity.id }),- ...lookupWindow(entity.createdAt),+ ...getSummarizationLookupDateRange(entity.createdAt),}const data = await llmAnalyticsSummarizationCreate(String(teamId), request).catch((error: unknown) => {diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.tsindex 037c95ffe225..07a93e654d99 100644--- a/products/ai_observability/frontend/utils.test.ts+++ b/products/ai_observability/frontend/utils.test.ts@@ -13,6 +13,7 @@ import {getInternalTagName,getSessionID,getSessionStartTimestamp,+ getSummarizationLookupDateRange,hasCostBreakdown,hasStringContentField,isEmptyJSONStructure,@@ -139,6 +140,24 @@ describe('mapEvaluationRunRow', () => {})})+describe('getSummarizationLookupDateRange', () => {+ it('brackets the entity timestamp by a day either side', () => {+ expect(getSummarizationLookupDateRange('2026-01-01T00:00:00Z')).toEqual({+ date_from: '2025-12-31T00:00:00.000Z',+ date_to: '2026-01-02T00:00:00.000Z',+ })+ })++ // Without the guard, dayjs anchors on now, so the window never contains an older entity+ // and the endpoint answers 404 instead of falling back to its own default.+ it.each([+ ['missing', undefined],+ ['unparseable', 'not a timestamp'],+ ])('sends no window at all when the timestamp is %s', (_, createdAt) => {+ expect(getSummarizationLookupDateRange(createdAt)).toEqual({})+ })+})+// The recipe-based `RecipeNormalizer` in `./normalizer` is the production code path.const recipe = new RecipeNormalizer()const IMPLS = [diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.tsindex e2977061627d..c3f5c19b1551 100644--- a/products/ai_observability/frontend/utils.ts+++ b/products/ai_observability/frontend/utils.ts@@ -14,6 +14,7 @@ import {EVALUATION_RUNS_QUERY_LIMIT,} from './evaluations/constants'import type { EvaluationOutputType, EvaluationRun, EvaluationType } from './evaluations/types'+import type { SummarizeRequestApi } from './generated/api.schemas'import {AnthropicDocumentMessage,AnthropicImageMessage,@@ -292,6 +293,33 @@ export function isTraceLevel(item: LLMTrace | LLMTraceEvent): item is LLMTrace {return !isLLMEvent(item)}+/**+ * Days either side of the entity's own timestamp to search for it, instead of the endpoint's 30-day+ * default. Narrow keeps the lookup off traces that reuse a customer-supplied ID, and a single trace+ * rarely spans longer than this.+ */+const SUMMARIZATION_LOOKUP_WINDOW_DAYS = 1++/**+ * Date window for summarization requests that reference a trace or event by ID.+ *+ * The endpoint refetches the entity itself, so the window is all it has to find it by. Callers that+ * cannot produce a usable timestamp get an empty range, which leaves the endpoint's own default in+ * place rather than sending a window that excludes the entity.+ */+export function getSummarizationLookupDateRange(+ createdAt: string | undefined+): Pick<SummarizeRequestApi, 'date_from' | 'date_to'> {+ const timestamp = createdAt ? dayjs(createdAt) : null+ if (!timestamp?.isValid()) {+ return {}+ }+ return {+ date_from: timestamp.subtract(SUMMARIZATION_LOOKUP_WINDOW_DAYS, 'day').toISOString(),+ date_to: timestamp.add(SUMMARIZATION_LOOKUP_WINDOW_DAYS, 'day').toISOString(),+ }+}+function normalizeSessionId(value: unknown): string | null {return typeof value === 'string' && value.length > 0 ? value : null}