: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): stop sentiment tab running out of query memory (#88536)
Bernat Torres397710064a36
diff --git a/products/ai_observability/frontend/sentimentQueries.test.ts b/products/ai_observability/frontend/sentimentQueries.test.tsindex 050e2a36d11b..944cb94e659f 100644--- a/products/ai_observability/frontend/sentimentQueries.test.ts+++ b/products/ai_observability/frontend/sentimentQueries.test.ts@@ -167,46 +167,53 @@ describe('sentimentQueries', () => {expect(mockApi.queryHogQL.mock.calls[1][0]).toContain('FROM events')})- it('builds sentiment tab rows from evaluated generations and ai_events input', async () => {- mockApi.queryHogQL- .mockResolvedValueOnce({- columns: candidateColumns,- results: [['evaluation-0', 'trace-0', 'generation-0']],- })- .mockResolvedValueOnce({- columns: generationColumns,- results: [generationRow(0)],+ it.each<[string, boolean]>([+ ['excluding test accounts', true],+ ['including test accounts', false],+ ])(+ 'builds sentiment tab rows from evaluated generations and ai_events input (%s)',+ async (_, shouldFilterTestAccounts) => {+ mockApi.queryHogQL+ .mockResolvedValueOnce({+ columns: candidateColumns,+ results: [['evaluation-0', 'trace-0', 'generation-0']],+ })+ .mockResolvedValueOnce({+ columns: generationColumns,+ results: [generationRow(0)],+ })++ const page = await fetchSentimentGenerationsPage({ ...queryValues, shouldFilterTestAccounts }, 0)++ expect(page.rawCount).toBe(1)+ expect(page.hasMore).toBe(false)+ expect(page.generations).toHaveLength(1)+ expect(page.generations[0]).toMatchObject({+ uuid: 'generation-0',+ traceId: 'trace-0',+ aiInput: JSON.stringify([{ role: 'user', content: 'this was great' }]),+ sentiment: {+ label: 'positive',+ score: 0.91,+ },})- const page = await fetchSentimentGenerationsPage(queryValues, 0)-- expect(page.rawCount).toBe(1)- expect(page.hasMore).toBe(false)- expect(page.generations).toHaveLength(1)- expect(page.generations[0]).toMatchObject({- uuid: 'generation-0',- traceId: 'trace-0',- aiInput: JSON.stringify([{ role: 'user', content: 'this was great' }]),- sentiment: {- label: 'positive',- score: 0.91,- },- })-- expect(mockApi.queryHogQL).toHaveBeenCalledTimes(2)- const [candidateQuery, , candidateOptions] = mockApi.queryHogQL.mock.calls[0]- expect(candidateQuery).toContain("JSONExtractFloat(scores, 'positive')")- expect(candidateQuery).toContain("JSONExtractFloat(scores, 'negative')")- expect(candidateQuery).toContain('toIntOrZero(message_count) > 0')- expect(candidateOptions?.queryParams?.filters).toEqual({- dateRange: { date_from: '-7d', date_to: null },- })+ expect(mockApi.queryHogQL).toHaveBeenCalledTimes(2)+ const [candidateQuery, , candidateOptions] = mockApi.queryHogQL.mock.calls[0]+ expect(candidateQuery).toContain("JSONExtractFloat(scores, 'positive')")+ expect(candidateQuery).toContain("JSONExtractFloat(scores, 'negative')")+ expect(candidateQuery).toContain('toIntOrZero(message_count) > 0')+ expect(candidateOptions?.queryParams?.filters).toEqual({+ dateRange: { date_from: '-7d', date_to: null },+ filterTestAccounts: shouldFilterTestAccounts,+ })- const [, , hydrationOptions] = mockApi.queryHogQL.mock.calls[1]- expect(hydrationOptions?.queryParams?.filters).toEqual({- filterTestAccounts: false,- })- })+ // Project filters belong on the candidate query above. A person property filter here+ // would join ai_events back to the main cluster.+ const [, , hydrationOptions] = mockApi.queryHogQL.mock.calls[1]+ expect(hydrationOptions?.queryParams).toBeUndefined()+ }+ )it('restricts the candidate query to a single evaluation when one is selected', async () => {mockApi.queryHogQLdiff --git a/products/ai_observability/frontend/sentimentQueries.ts b/products/ai_observability/frontend/sentimentQueries.tsindex 97df17e5facb..26dd77a39b49 100644--- a/products/ai_observability/frontend/sentimentQueries.ts+++ b/products/ai_observability/frontend/sentimentQueries.ts@@ -327,6 +327,7 @@ async function fetchSentimentEvaluationCandidates(date_from: values.dateFilter.dateFrom,date_to: values.dateFilter.dateTo,},+ filterTestAccounts: values.shouldFilterTestAccounts,},},}@@ -346,9 +347,16 @@ async function fetchSentimentEvaluationCandidates(return candidates}+/**+ * Fetches the content behind an exact list of generations.+ *+ * This query takes no project filters. The candidate query applies them, and this query needs+ * only the keys that query returns. A person property filter is also far more expensive here:+ * `events` reads person properties from a denormalized column, but `ai_events` resolves them+ * through a join back to the main cluster, which can exhaust query memory.+ */async function hydrateSentimentGenerations(candidates: SentimentEvaluationCandidate[],- values: SentimentGenerationsQueryValues,refresh?: RefreshType): Promise<Map<string, SentimentGeneration>> {const traceIds = uniqueNonEmpty(candidates.map((candidate) => candidate.traceId))@@ -387,7 +395,6 @@ async function hydrateSentimentGenerations(WHERE event = '$ai_generation'AND trace_id IN ${traceIds}AND toString(uuid) IN ${generationIds}- AND {filters}GROUP BY uuid, trace_id) AS generationINNER JOIN (@@ -412,14 +419,7 @@ async function hydrateSentimentGenerations(LIMIT ${generationIds.length}`,{ ...SENTIMENT_QUERY_TAGS, name: 'ai_observability_sentiment_generation_hydration' },- {- refresh,- queryParams: {- filters: {- filterTestAccounts: values.shouldFilterTestAccounts,- },- },- }+ { refresh })const columnIndexes = buildQueryColumnIndexes(response.columns, SENTIMENT_GENERATION_COLUMNS)@@ -481,7 +481,7 @@ export async function fetchSentimentGenerationsPage(break}- const generationById = await hydrateSentimentGenerations(candidates, values, refresh)+ const generationById = await hydrateSentimentGenerations(candidates, refresh)let consumedCandidates = 0for (const candidate of candidates) {