: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): rank sentiment evaluations before loading traces (#79103)
Radu Raicea1b062fa8b70d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 3531fcbfd30f..6fb97aa58528 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6265,7 +6265,7 @@ snapshots:scenes-app-inbox-scene--self-driving-paused--dark:hash: v1.k794b7964.bd2bee28eee6668bfd9f1e5c00191e38189bc27ac734c8adf8ddc55da8381b1b.HFfADdkZDnQv2BGCHc-yzXZ4Z0Rpk-xn9cn7uRUXIygscenes-app-inbox-scene--self-driving-paused--light:- hash: v1.k794b7964.5f8c26b5f2a35d63e9e3817ee3c8923ca19d249bef13d8e78196f3a544d5451d.iDetyRF2JiZuSAhHnuuzMdBenEEdjTxlgKUbmQ-bmSk+ hash: v1.k794b7964.54f6835c7d4a343bd6c9efef4189805b8dc5ea3347380b5d772ce55abaad79be.P7Ramt_0TgHAl4YgBsBumQ1QVxkb2ds9GsTaxbNAKRQscenes-app-inbox-tabs--pull-requests--dark:hash: v1.k794b7964.474d8e744637e08afd4bb7540f0f5dafd6a79342c2f547188cb436b55f9ef8e7.PiyD1Zkhkot-_DKLU3W0T5uA7rvpTUTn5bKChCa3AV4scenes-app-inbox-tabs--pull-requests--light:diff --git a/frontend/src/lib/components/DateFilter/DateFilter.test.tsx b/frontend/src/lib/components/DateFilter/DateFilter.test.tsxindex 7ae81b7485e9..8611b9acd7c7 100644--- a/frontend/src/lib/components/DateFilter/DateFilter.test.tsx+++ b/frontend/src/lib/components/DateFilter/DateFilter.test.tsx@@ -103,3 +103,31 @@ describe('DateFilter with allowFixedRangeWithTime', () => {})})})++describe('DateFilter without custom ranges', () => {+ beforeEach(() => {+ initKeaTests()+ render(+ <Provider>+ <DateFilter+ onChange={jest.fn()}+ dateOptions={dateMapping.filter(({ values }) => values[0] === '-1h')}+ showRollingRangePicker={false}+ showCustomRangeOptions={false}+ />+ </Provider>+ )+ })++ afterEach(() => {+ cleanup()+ })++ it('only shows the supplied presets', async () => {+ await userEvent.click(screen.getByTestId('date-filter'))++ expect(screen.getByText('Last hour')).toBeInTheDocument()+ expect(screen.queryByTestId('rolling-date-range-input')).not.toBeInTheDocument()+ expect(screen.queryByText(/custom/i)).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/lib/components/DateFilter/DateFilter.tsx b/frontend/src/lib/components/DateFilter/DateFilter.tsxindex e8c6fa3c8801..39503af1ad93 100644--- a/frontend/src/lib/components/DateFilter/DateFilter.tsx+++ b/frontend/src/lib/components/DateFilter/DateFilter.tsx@@ -39,6 +39,7 @@ import { DateOption } from './rollingDateRangeFilterLogic'export interface DateFilterProps {showCustom?: booleanshowRollingRangePicker?: boolean+ showCustomRangeOptions?: booleanmakeLabel?: (key: React.ReactNode, startOfRange?: React.ReactNode, endOfRange?: React.ReactNode) => React.ReactNodeclassName?: stringonChange?: (fromDate: string | null, toDate: string | null, explicitDate?: boolean) => void@@ -95,6 +96,7 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(func{showCustom,showRollingRangePicker = true,+ showCustomRangeOptions = true,className,disabledReason,makeLabel,@@ -200,6 +202,7 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(funcconst showFixedRangeTimeToggle = allowTimePrecision || allowFixedRangeWithTimeconst showExclusions =(showIncompletePeriodExclusion || showDaysOfWeekExclusions) && !!exclusions && !!onExclusionsChange+ const showFooter = showCustomRangeOptions || showExplicitDateToggle || showExclusions || showJumpToTimestampconst popoverOverlay =view === DateFilterView.FixedRange ? (@@ -280,7 +283,7 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(funcdirection="vertical"hideScrollbars// max-h-80 shows ~9 preset rows with a sliver of the tenth as a scroll hint- className={clsx('min-h-0 flex-1 border-b', optionsSize === 'small' && 'max-h-80')}+ className={clsx('min-h-0 flex-1', showFooter && 'border-b', optionsSize === 'small' && 'max-h-80')}innerClassName="deprecated-space-y-px p-1">{dateOptions.map(({ key, values, inactive }) => {@@ -363,92 +366,104 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(func/>)}</ScrollableShadows>- <div className="shrink-0 deprecated-space-y-px p-1">- {(isFixedDateMode || allowSingleAndRange) && (- <LemonButton onClick={openFixedDate} active={isFixedDate} size={optionsSize} fullWidth>- Custom date...- </LemonButton>- )}- {(!isFixedDateMode || allowSingleAndRange) && (- <>- {!allowSingleAndRange && (- <LemonButton onClick={openDateToNow} active={isDateToNow} size={optionsSize} fullWidth>- From custom date until now…- </LemonButton>- )}- <LemonButton onClick={openFixedRange} active={isFixedRange} size={optionsSize} fullWidth>- Custom fixed date range…+ {showFooter && (+ <div className="shrink-0 deprecated-space-y-px p-1">+ {showCustomRangeOptions && (isFixedDateMode || allowSingleAndRange) && (+ <LemonButton onClick={openFixedDate} active={isFixedDate} size={optionsSize} fullWidth>+ Custom date...</LemonButton>- {effectiveShowCustomRelativeRange && (+ )}+ {showCustomRangeOptions && (!isFixedDateMode || allowSingleAndRange) && (+ <>+ {!allowSingleAndRange && (+ <LemonButton+ onClick={openDateToNow}+ active={isDateToNow}+ size={optionsSize}+ fullWidth+ >+ From custom date until now…+ </LemonButton>+ )}<LemonButton- onClick={openCustomRelativeRange}- active={isCustomRelativeRange}+ onClick={openFixedRange}+ active={isFixedRange}size={optionsSize}fullWidth>- Custom relative range…+ Custom fixed date range…</LemonButton>- )}- </>- )}- {(showExplicitDateToggle || showExclusions) && <LemonDivider />}- {showExplicitDateToggle && (- <div- className={clsx(- // Deliberately medium at every optionsSize: LemonButton--small keeps the default- // 14px font, while LemonSwitch--small would drop the label to 12px- 'LemonSwitch LemonSwitch--full-width LemonSwitch--medium',- optionsSize === 'small' ? 'pb-1 pt-1' : 'pb-2 pt-2'- )}- >- <label className="flex items-center gap-1">- <span>Exact time range</span>- <Tooltip- title={- <>- <div className="font-semibold mb-1">When enabled:</div>- <div className="mb-2">- Uses the current time for period boundaries instead of full days.- </div>- <div className="font-semibold mb-1">When disabled:</div>- <div>Dates are rounded to full day periods (start and end of day).</div>- </>- }- >- <IconInfo className="text-muted-alt w-4 h-4" />- </Tooltip>- </label>- <LemonSwitch- checked={explicitDate ?? false}- onChange={(checked) => {- setExplicitDate(checked)- }}- />- </div>- )}- {showExclusions && (- <LemonDateFilterExclusions- exclusions={exclusions}- onChange={onExclusionsChange}- showDays={showDaysOfWeekExclusions}- showIncomplete={showIncompletePeriodExclusion}- size={optionsSize}- />- )}- {showJumpToTimestamp && (- <>- <LemonDivider />- <LemonButton- onClick={openJumpToTimestamp}- size={optionsSize}- fullWidth- data-attr="jump-to-timestamp-option"+ {effectiveShowCustomRelativeRange && (+ <LemonButton+ onClick={openCustomRelativeRange}+ active={isCustomRelativeRange}+ size={optionsSize}+ fullWidth+ >+ Custom relative range…+ </LemonButton>+ )}+ </>+ )}+ {showCustomRangeOptions && (showExplicitDateToggle || showExclusions) && <LemonDivider />}+ {showExplicitDateToggle && (+ <div+ className={clsx(+ // Deliberately medium at every optionsSize: LemonButton--small keeps the default+ // 14px font, while LemonSwitch--small would drop the label to 12px+ 'LemonSwitch LemonSwitch--full-width LemonSwitch--medium',+ optionsSize === 'small' ? 'pb-1 pt-1' : 'pb-2 pt-2'+ )}>- Jump to timestamp…- </LemonButton>- </>- )}- </div>+ <label className="flex items-center gap-1">+ <span>Exact time range</span>+ <Tooltip+ title={+ <>+ <div className="font-semibold mb-1">When enabled:</div>+ <div className="mb-2">+ Uses the current time for period boundaries instead of full days.+ </div>+ <div className="font-semibold mb-1">When disabled:</div>+ <div>Dates are rounded to full day periods (start and end of day).</div>+ </>+ }+ >+ <IconInfo className="text-muted-alt w-4 h-4" />+ </Tooltip>+ </label>+ <LemonSwitch+ checked={explicitDate ?? false}+ onChange={(checked) => {+ setExplicitDate(checked)+ }}+ />+ </div>+ )}+ {showExclusions && (+ <LemonDateFilterExclusions+ exclusions={exclusions}+ onChange={onExclusionsChange}+ showDays={showDaysOfWeekExclusions}+ showIncomplete={showIncompletePeriodExclusion}+ size={optionsSize}+ />+ )}+ {showJumpToTimestamp && (+ <>+ <LemonDivider />+ <LemonButton+ onClick={openJumpToTimestamp}+ size={optionsSize}+ fullWidth+ data-attr="jump-to-timestamp-option"+ >+ Jump to timestamp…+ </LemonButton>+ </>+ )}+ </div>+ )}</div>)diff --git a/products/ai_observability/frontend/AIObservabilityScene.tsx b/products/ai_observability/frontend/AIObservabilityScene.tsxindex d27aaabe6c67..a2fb0c5de97b 100644--- a/products/ai_observability/frontend/AIObservabilityScene.tsx+++ b/products/ai_observability/frontend/AIObservabilityScene.tsx@@ -14,6 +14,7 @@ import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitchimport { dayjs } from 'lib/dayjs'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'+import { dateMapping } from 'lib/utils/dateFilters'import { objectsEqual } from 'lib/utils/objects'import { EventDetails } from 'scenes/activity/explore/EventDetails'import { Dashboard } from 'scenes/dashboard/Dashboard'@@ -67,6 +68,11 @@ export const scene: SceneExport = {emptyState: aiObservabilityEmptyState,}+const SENTIMENT_DATE_VALUES = new Set(['-1h', '-24h', '-7d', '-14d', '-30d'])+const SENTIMENT_DATE_OPTIONS = dateMapping.filter(({ values }) =>+ values.some((value) => SENTIMENT_DATE_VALUES.has(value))+)+const Filters = ({ hidePropertyFilters = false }: { hidePropertyFilters?: boolean }): JSX.Element => {const { dashboardDateFilter, dateFilter, shouldFilterTestAccounts, propertyFilters, activeTab } =useValues(aiObservabilitySharedLogic)@@ -79,7 +85,14 @@ const Filters = ({ hidePropertyFilters = false }: { hidePropertyFilters?: booleareturn (<div className="flex gap-x-4 gap-y-2 items-center flex-wrap py-4 -mt-4 mb-4 border-b">- <DateFilter dateFrom={dateFrom} dateTo={dateTo} onChange={setDates} />+ <DateFilter+ dateFrom={dateFrom}+ dateTo={dateTo}+ onChange={setDates}+ dateOptions={activeTab === 'sentiment' ? SENTIMENT_DATE_OPTIONS : undefined}+ showRollingRangePicker={activeTab !== 'sentiment'}+ showCustomRangeOptions={activeTab !== 'sentiment'}+ />{!hidePropertyFilters && (<><PropertyFiltersdiff --git a/products/ai_observability/frontend/sentimentQueries.test.ts b/products/ai_observability/frontend/sentimentQueries.test.tsindex 254551e5f822..d885e55b8528 100644--- a/products/ai_observability/frontend/sentimentQueries.test.ts+++ b/products/ai_observability/frontend/sentimentQueries.test.ts@@ -6,13 +6,76 @@ jest.mock('lib/api')const mockApi = api as jest.Mocked<typeof api>+const storedSentimentColumns = [+ 'trace_id',+ 'generation_id',+ 'label',+ 'score',+ 'scores',+ 'messages',+ 'message_count',+ 'evaluation_timestamp',+]+const candidateColumns = ['evaluation_id', 'trace_id', 'generation_id']+const generationColumns = [+ 'uuid',+ 'trace_id',+ 'generation_id',+ 'model',+ 'distinct_id',+ 'generation_timestamp',+ 'ai_input',+ 'label',+ 'score',+ 'scores',+ 'messages',+ 'message_count',+]++const queryValues = {+ dateFilter: { dateFrom: '-7d', dateTo: null },+ shouldFilterTestAccounts: false,+ propertyFilters: [],+}++function candidateRows(count: number, start: number = 0): unknown[][] {+ return Array.from({ length: count }, (_, index) => {+ const candidateIndex = start + index+ return [`evaluation-${candidateIndex}`, `trace-${candidateIndex}`, `generation-${candidateIndex}`]+ })+}++function generationRow(index: number): unknown[] {+ return [+ `generation-${index}`,+ `trace-${index}`,+ null,+ 'gpt-4.1',+ `distinct-${index}`,+ '2026-06-23T10:00:00Z',+ JSON.stringify([{ role: 'user', content: 'this was great' }]),+ 'positive',+ '0.91',+ { positive: 0.91, neutral: 0.08, negative: 0.01 },+ {+ '0': {+ label: 'positive',+ score: 0.91,+ scores: { positive: 0.91, neutral: 0.08, negative: 0.01 },+ },+ },+ 1,+ ]+}+describe('sentimentQueries', () => {beforeEach(() => {jest.resetAllMocks()})it('reads stored generation sentiment from ai_events first', async () => {- jest.spyOn(mockApi, 'queryHogQL').mockResolvedValueOnce({+ mockApi.queryHogQL.mockResolvedValueOnce({+ columns: storedSentimentColumns,results: [['trace-1',@@ -31,7 +94,7 @@ describe('sentimentQueries', () => {'2026-06-23T10:00:00Z',],],- } as any)+ })const results = await fetchStoredGenerationSentiments([{@@ -56,9 +119,10 @@ describe('sentimentQueries', () => {})it('falls back to events when stored generation sentiment is missing from ai_events', async () => {- jest.spyOn(mockApi, 'queryHogQL')- .mockResolvedValueOnce({ results: [] } as any)+ mockApi.queryHogQL+ .mockResolvedValueOnce({ columns: storedSentimentColumns, results: [] }).mockResolvedValueOnce({+ columns: storedSentimentColumns,results: [['trace-1',@@ -77,7 +141,7 @@ describe('sentimentQueries', () => {'2026-06-23T10:00:00Z',],],- } as any)+ })const results = await fetchStoredGenerationSentiments([{@@ -98,55 +162,77 @@ describe('sentimentQueries', () => {})it('builds sentiment tab rows from evaluated generations and ai_events input', async () => {- jest.spyOn(mockApi, 'query').mockResolvedValue({- results: [['generation-uuid', 'trace-1', null, 'gpt-4.1', 'distinct-1', '2026-06-23T10:00:00Z']],- } as any)- jest.spyOn(mockApi, 'queryHogQL')+ mockApi.queryHogQL.mockResolvedValueOnce({- results: [- [- 'trace-1',- 'generation-uuid',- 'positive',- '0.91',- { positive: 0.91, neutral: 0.08, negative: 0.01 },- {- '0': {- label: 'positive',- score: 0.91,- scores: { positive: 0.91, neutral: 0.08, negative: 0.01 },- },- },- 1,- '2026-06-23T10:00:01Z',- ],- ],- } as any)+ columns: candidateColumns,+ results: [['evaluation-0', 'trace-0', 'generation-0']],+ }).mockResolvedValueOnce({- results: [- ['generation-uuid', 'trace-1', JSON.stringify([{ role: 'user', content: 'this was great' }])],- ],- } as any)+ columns: generationColumns,+ results: [generationRow(0)],+ })- const page = await fetchSentimentGenerationsPage(- {- dateFilter: { dateFrom: '-7d', dateTo: null },- shouldFilterTestAccounts: false,- propertyFilters: [],- },- 0- )+ 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-uuid',- traceId: 'trace-1',+ 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 },+ })++ const [, , hydrationOptions] = mockApi.queryHogQL.mock.calls[1]+ expect(hydrationOptions?.queryParams?.filters).toEqual({+ filterTestAccounts: false,+ properties: [],+ })+ })++ it('does not fall back to events when ai_events no longer retains a generation input', async () => {+ mockApi.queryHogQL+ .mockResolvedValueOnce({+ columns: candidateColumns,+ results: [['evaluation-0', 'trace-0', 'generation-0']],+ })+ .mockResolvedValueOnce({ columns: generationColumns, results: [] })++ const page = await fetchSentimentGenerationsPage(queryValues, 0)++ expect(page.rawCount).toBe(1)+ expect(page.hasMore).toBe(false)+ expect(page.generations).toEqual([])+ expect(mockApi.queryHogQL).toHaveBeenCalledTimes(2)+ })++ it('backfills candidates removed by generation filters', async () => {+ mockApi.queryHogQL+ .mockResolvedValueOnce({ columns: candidateColumns, results: candidateRows(200) })+ .mockResolvedValueOnce({ columns: generationColumns, results: [] })+ .mockResolvedValueOnce({ columns: candidateColumns, results: candidateRows(1, 200) })+ .mockResolvedValueOnce({ columns: generationColumns, results: [generationRow(200)] })++ const page = await fetchSentimentGenerationsPage(queryValues, 0)++ expect(page.generations).toHaveLength(1)+ expect(page.generations[0].uuid).toBe('generation-200')+ expect(page.rawCount).toBe(201)+ expect(page.hasMore).toBe(false)+ expect(mockApi.queryHogQL).toHaveBeenCalledTimes(4)+ expect(mockApi.queryHogQL.mock.calls[2][0]).toContain('OFFSET 200')})})diff --git a/products/ai_observability/frontend/sentimentQueries.ts b/products/ai_observability/frontend/sentimentQueries.tsindex 6824873d8cb9..c95ae3b6fe5b 100644--- a/products/ai_observability/frontend/sentimentQueries.ts+++ b/products/ai_observability/frontend/sentimentQueries.ts@@ -1,6 +1,6 @@import api from 'lib/api'-import { EventsQuery, NodeKind, ProductKey } from '~/queries/schema/schema-general'+import { ProductKey } from '~/queries/schema/schema-general'import { hogql } from '~/queries/utils'import { AnyPropertyFilter } from '~/types'@@ -13,41 +13,56 @@ const SENTIMENT_QUERY_TAGS = {scene: 'ai_observability_sentiment',}-const SENTIMENT_GENERATION_SELECT = [- 'uuid',- 'properties.$ai_trace_id',- 'properties.$ai_generation_id',- 'properties.$ai_model',- 'distinct_id',- 'timestamp',-] as const-const EVALUATION_TARGET_ID_SELECT = `ifNull(nullIf(nullIf(toString(properties.$ai_target_event_id), ''), 'null'), '')`-type SentimentEvaluationQueryRow = [string, string, unknown, unknown, unknown, unknown, unknown, unknown]-type GenerationInputQueryRow = [string, string, unknown]+const STORED_SENTIMENT_COLUMNS = [+ 'trace_id',+ 'generation_id',+ 'label',+ 'score',+ 'scores',+ 'messages',+ 'message_count',+] as const++const SENTIMENT_EVALUATION_CANDIDATE_COLUMNS = ['evaluation_id', 'trace_id', 'generation_id'] as const++const SENTIMENT_GENERATION_COLUMNS = [+ 'uuid',+ 'trace_id',+ 'generation_id',+ 'model',+ 'distinct_id',+ 'generation_timestamp',+ 'ai_input',+ 'label',+ 'score',+ 'scores',+ 'messages',+ 'message_count',+] as constinterface SentimentQuerySource {from: stringtraceIdExpression: string}-interface GenerationInputQuerySource extends SentimentQuerySource {- inputExpression: string-}--const AI_EVENTS_SOURCE: GenerationInputQuerySource = {+const AI_EVENTS_SOURCE: SentimentQuerySource = {from: 'posthog.ai_events AS ai_events',traceIdExpression: 'trace_id',- inputExpression: 'input',}-const EVENTS_SOURCE: GenerationInputQuerySource = {+const EVENTS_SOURCE: SentimentQuerySource = {from: 'events',traceIdExpression: 'properties.$ai_trace_id',- inputExpression: 'properties.$ai_input',+}++interface SentimentEvaluationCandidate {+ evaluationId: string+ traceId: string+ generationId: string}export interface GenerationSentimentLookup {@@ -78,6 +93,7 @@ export interface SentimentGenerationsQueryValues {export interface SentimentGenerationsPage {generations: SentimentGeneration[]rawCount: number+ hasMore: boolean}function normalizeString(value: unknown): string {@@ -98,32 +114,34 @@ function uniqueNonEmpty(values: string[]): string[] {return Array.from(new Set(values.filter(Boolean)))}-function hasUsableInput(value: unknown): boolean {- return value !== null && value !== undefined && value !== '' && value !== 'null'-}--function mapGenerationRow(row: unknown[]): SentimentGeneration | null {- const uuid = normalizeString(row[0])- const traceId = normalizeString(row[1])-- if (!uuid || !traceId) {- return null+function buildQueryColumnIndexes(+ columns: unknown[] | undefined,+ requiredColumns: readonly string[]+): Map<string, number> {+ const availableColumns = (columns ?? []).map(normalizeString)+ const indexes = new Map<string, number>()++ for (const column of requiredColumns) {+ const index = availableColumns.indexOf(column)+ if (index === -1) {+ throw new Error(`Query response is missing the ${column} column`)+ }+ indexes.set(column, index)}- const generationPropertyId = normalizeString(row[2])- const timestamp = normalizeString(row[5])+ return indexes+}- return {- uuid,- traceId,- generationIds: uniqueNonEmpty([uuid, generationPropertyId]),- aiInput: null,- model: normalizeNullableString(row[3]),- distinctId: normalizeString(row[4]),- timestamp,- createdAt: timestamp,- sentiment: null,+function queryColumnValue(row: unknown[], columnIndexes: Map<string, number>, column: string): unknown {+ const index = columnIndexes.get(column)+ if (index === undefined) {+ throw new Error(`Query response has no index for the ${column} column`)}+ return row[index]+}++function hasUsableInput(value: unknown): boolean {+ return value !== null && value !== undefined && value !== '' && value !== 'null'}async function queryStoredGenerationSentiments(@@ -137,7 +155,7 @@ async function queryStoredGenerationSentiments(return new Map()}- const response = await api.queryHogQL<SentimentEvaluationQueryRow[]>(+ const response = await api.queryHogQL<unknown[][]>(hogql`SELECTtrace_id,@@ -171,19 +189,20 @@ async function queryStoredGenerationSentiments({ ...SENTIMENT_QUERY_TAGS, name: 'ai_observability_generation_sentiment_lookup' })+ const columnIndexes = buildQueryColumnIndexes(response.columns, STORED_SENTIMENT_COLUMNS)const sentimentByTargetId = new Map<string, GenerationSentiment>()- for (const row of response?.results || []) {- const [, generationId, label, score, scores, messages, messageCount] = row+ for (const row of response.results) {+ const generationId = normalizeString(queryColumnValue(row, columnIndexes, 'generation_id'))const normalized = normalizeSentimentResult({- label,- score,- scores,- messages,- message_count: messageCount,+ label: queryColumnValue(row, columnIndexes, 'label'),+ score: queryColumnValue(row, columnIndexes, 'score'),+ scores: queryColumnValue(row, columnIndexes, 'scores'),+ messages: queryColumnValue(row, columnIndexes, 'messages'),+ message_count: queryColumnValue(row, columnIndexes, 'message_count'),})- if (generationId && normalized) {- sentimentByTargetId.set(String(generationId), normalized)+ if (generationId) {+ sentimentByTargetId.set(generationId, normalized)}}@@ -242,125 +261,227 @@ export async function fetchStoredGenerationSentiments(return results}-async function queryGenerationInputs(- generations: SentimentGeneration[],- source: GenerationInputQuerySource-): Promise<Map<string, unknown>> {- const traceIds = uniqueNonEmpty(generations.map((generation) => generation.traceId))- const generationEventIds = uniqueNonEmpty(generations.map((generation) => generation.uuid))-- if (traceIds.length === 0 || generationEventIds.length === 0) {- return new Map()- }-- const response = await api.queryHogQL<GenerationInputQueryRow[]>(+async function fetchSentimentEvaluationCandidates(+ values: SentimentGenerationsQueryValues,+ offset: number+): Promise<SentimentEvaluationCandidate[]> {+ const response = await api.queryHogQL<unknown[][]>(hogql`SELECT- uuid,+ evaluation_id,trace_id,- argMax(ai_input, timestamp) AS ai_input+ generation_idFROM (SELECT- toString(uuid) AS uuid,- ${hogql.raw(source.traceIdExpression)} AS trace_id,- timestamp,- ${hogql.raw(source.inputExpression)} AS ai_input- FROM ${hogql.raw(source.from)}- WHERE event = '$ai_generation'- AND ${hogql.raw(source.traceIdExpression)} IN ${traceIds}- AND toString(uuid) IN ${generationEventIds}+ properties.$ai_trace_id AS trace_id,+ ${hogql.raw(EVALUATION_TARGET_ID_SELECT)} AS generation_id,+ argMax(toString(uuid), timestamp) AS evaluation_id,+ argMax(toString(properties.$ai_sentiment_label), timestamp) AS label,+ argMax(toString(properties.$ai_sentiment_scores), timestamp) AS scores,+ argMax(toString(properties.$ai_sentiment_message_count), timestamp) AS message_count,+ max(timestamp) AS evaluation_timestamp+ FROM events+ WHERE event = '$ai_evaluation'+ AND properties.$ai_evaluation_runtime = 'sentiment'+ AND timestamp >= now() - INTERVAL 30 DAY+ AND {filters}+ GROUP BY trace_id, generation_id)- WHERE length(uuid) > 0+ WHERE length(evaluation_id) > 0AND length(trace_id) > 0- GROUP BY uuid, trace_id- LIMIT ${Math.max(generationEventIds.length, 1)}+ AND length(generation_id) > 0+ AND label IN ('positive', 'negative', 'neutral')+ AND toIntOrZero(message_count) > 0+ ORDER BY greatest(+ JSONExtractFloat(scores, 'positive'),+ JSONExtractFloat(scores, 'negative')+ ) DESC, evaluation_timestamp DESC, generation_id DESC+ LIMIT ${GENERATIONS_PAGE_SIZE}+ OFFSET ${Math.max(0, Math.trunc(offset))}`,- { ...SENTIMENT_QUERY_TAGS, name: 'ai_observability_generation_input_lookup' }+ { ...SENTIMENT_QUERY_TAGS, name: 'ai_observability_sentiment_evaluations' },+ {+ queryParams: {+ filters: {+ dateRange: {+ date_from: values.dateFilter.dateFrom,+ date_to: values.dateFilter.dateTo,+ },+ },+ },+ })- const inputs = new Map<string, unknown>()- for (const [uuid, , aiInput] of response?.results || []) {- if (uuid && hasUsableInput(aiInput)) {- inputs.set(String(uuid), aiInput)+ const columnIndexes = buildQueryColumnIndexes(response.columns, SENTIMENT_EVALUATION_CANDIDATE_COLUMNS)+ const candidates: SentimentEvaluationCandidate[] = []+ for (const row of response.results) {+ const evaluationId = normalizeString(queryColumnValue(row, columnIndexes, 'evaluation_id'))+ const traceId = normalizeString(queryColumnValue(row, columnIndexes, 'trace_id'))+ const generationId = normalizeString(queryColumnValue(row, columnIndexes, 'generation_id'))++ if (evaluationId && traceId && generationId) {+ candidates.push({ evaluationId, traceId, generationId })}}- return inputs+ return candidates}-async function fetchGenerationInputs(generations: SentimentGeneration[]): Promise<Record<string, unknown>> {- const inputsByGenerationKey: Record<string, unknown> = {}- const missingInputs = generations.filter((generation) => {- if (hasUsableInput(generation.aiInput)) {- inputsByGenerationKey[generation.uuid] = generation.aiInput- return false- }- return true- })+async function hydrateSentimentGenerations(+ candidates: SentimentEvaluationCandidate[],+ values: SentimentGenerationsQueryValues+): Promise<Map<string, SentimentGeneration>> {+ const traceIds = uniqueNonEmpty(candidates.map((candidate) => candidate.traceId))+ const generationIds = uniqueNonEmpty(candidates.map((candidate) => candidate.generationId))+ const evaluationIds = uniqueNonEmpty(candidates.map((candidate) => candidate.evaluationId))- if (missingInputs.length === 0) {- return inputsByGenerationKey+ if (traceIds.length === 0 || generationIds.length === 0 || evaluationIds.length === 0) {+ return new Map()}- const aiEventsInputs = await queryGenerationInputs(missingInputs, AI_EVENTS_SOURCE)- for (const [uuid, aiInput] of aiEventsInputs) {- inputsByGenerationKey[uuid] = aiInput- }+ const response = await api.queryHogQL<unknown[][]>(+ hogql`+ SELECT+ generation.uuid,+ generation.trace_id,+ generation.generation_id,+ generation.model,+ generation.distinct_id,+ generation.generation_timestamp,+ generation.ai_input,+ sentiment.label,+ sentiment.score,+ sentiment.scores,+ sentiment.messages,+ sentiment.message_count+ FROM (+ SELECT+ toString(uuid) AS uuid,+ trace_id,+ argMax(generation_id, timestamp) AS generation_id,+ argMax(model, timestamp) AS model,+ argMax(distinct_id, timestamp) AS distinct_id,+ max(timestamp) AS generation_timestamp,+ argMax(input, timestamp) AS ai_input+ FROM posthog.ai_events+ WHERE event = '$ai_generation'+ AND trace_id IN ${traceIds}+ AND toString(uuid) IN ${generationIds}+ AND {filters}+ GROUP BY uuid, trace_id+ ) AS generation+ INNER JOIN (+ SELECT+ trace_id,+ ${hogql.raw(EVALUATION_TARGET_ID_SELECT)} AS generation_id,+ argMax(toString(properties.$ai_sentiment_label), timestamp) AS label,+ argMax(toString(properties.$ai_sentiment_score), timestamp) AS score,+ argMax(properties.$ai_sentiment_scores, timestamp) AS scores,+ argMax(properties.$ai_sentiment_messages, timestamp) AS messages,+ argMax(toString(properties.$ai_sentiment_message_count), timestamp) AS message_count+ FROM posthog.ai_events+ WHERE event = '$ai_evaluation'+ AND properties.$ai_evaluation_runtime = 'sentiment'+ AND trace_id IN ${traceIds}+ AND toString(uuid) IN ${evaluationIds}+ GROUP BY trace_id, generation_id+ HAVING message_count != '0'+ ) AS sentiment+ ON generation.trace_id = sentiment.trace_id+ AND generation.uuid = sentiment.generation_id+ LIMIT ${generationIds.length}+ `,+ { ...SENTIMENT_QUERY_TAGS, name: 'ai_observability_sentiment_generation_hydration' },+ {+ queryParams: {+ filters: {+ filterTestAccounts: values.shouldFilterTestAccounts,+ properties: values.propertyFilters,+ },+ },+ }+ )- const fallbackGenerations = missingInputs.filter((generation) => !aiEventsInputs.has(generation.uuid))- if (fallbackGenerations.length === 0) {- return inputsByGenerationKey- }+ const columnIndexes = buildQueryColumnIndexes(response.columns, SENTIMENT_GENERATION_COLUMNS)+ const generationById = new Map<string, SentimentGeneration>()++ for (const row of response.results) {+ const uuid = normalizeString(queryColumnValue(row, columnIndexes, 'uuid'))+ const traceId = normalizeString(queryColumnValue(row, columnIndexes, 'trace_id'))+ const timestamp = normalizeString(queryColumnValue(row, columnIndexes, 'generation_timestamp'))+ const aiInput = queryColumnValue(row, columnIndexes, 'ai_input')+ const sentiment = normalizeSentimentResult({+ label: queryColumnValue(row, columnIndexes, 'label'),+ score: queryColumnValue(row, columnIndexes, 'score'),+ scores: queryColumnValue(row, columnIndexes, 'scores'),+ messages: queryColumnValue(row, columnIndexes, 'messages'),+ message_count: queryColumnValue(row, columnIndexes, 'message_count'),+ })++ if (!uuid || !traceId || !timestamp || (sentiment.message_count ?? 0) <= 0 || !hasUsableInput(aiInput)) {+ continue+ }- const eventsInputs = await queryGenerationInputs(fallbackGenerations, EVENTS_SOURCE)- for (const [uuid, aiInput] of eventsInputs) {- inputsByGenerationKey[uuid] = aiInput+ generationById.set(uuid, {+ uuid,+ traceId,+ generationIds: uniqueNonEmpty([+ uuid,+ normalizeString(queryColumnValue(row, columnIndexes, 'generation_id')),+ ]),+ aiInput,+ model: normalizeNullableString(queryColumnValue(row, columnIndexes, 'model')),+ distinctId: normalizeString(queryColumnValue(row, columnIndexes, 'distinct_id')),+ timestamp,+ createdAt: timestamp,+ sentiment,+ })}- return inputsByGenerationKey+ return generationById}export async function fetchSentimentGenerationsPage(values: SentimentGenerationsQueryValues,offset: number): Promise<SentimentGenerationsPage> {- const generationsQuery: EventsQuery = {- kind: NodeKind.EventsQuery,- event: '$ai_generation',- select: [...SENTIMENT_GENERATION_SELECT],- orderBy: ['timestamp DESC', 'uuid DESC'],- after: values.dateFilter.dateFrom || undefined,- before: values.dateFilter.dateTo || undefined,- filterTestAccounts: values.shouldFilterTestAccounts,- properties: values.propertyFilters,- limit: GENERATIONS_PAGE_SIZE,- offset,- tags: { ...SENTIMENT_QUERY_TAGS, name: 'ai_observability_sentiment_generations' },- }+ const generations: SentimentGeneration[] = []+ let rawCount = 0+ let hasMore = false++ while (generations.length < GENERATIONS_PAGE_SIZE) {+ const candidates = await fetchSentimentEvaluationCandidates(values, offset + rawCount)+ if (candidates.length === 0) {+ break+ }- const response = await api.query(generationsQuery)- const generationRows = (response?.results || [])- .map((row) => mapGenerationRow(row))- .filter((row): row is SentimentGeneration => row !== null)-- const [sentimentByGenerationKey, inputsByGenerationKey] = await Promise.all([- fetchStoredGenerationSentiments(- generationRows.map((generation) => ({- key: generation.uuid,- traceId: generation.traceId,- generationIds: generation.generationIds,- }))- ),- fetchGenerationInputs(generationRows),- ])+ const generationById = await hydrateSentimentGenerations(candidates, values)+ let consumedCandidates = 0++ for (const candidate of candidates) {+ consumedCandidates+++ const generation = generationById.get(candidate.generationId)+ if (generation) {+ generations.push(generation)+ }+ if (generations.length === GENERATIONS_PAGE_SIZE) {+ break+ }+ }++ rawCount += consumedCandidates+ const consumedEntireBatch = consumedCandidates === candidates.length+ if (generations.length === GENERATIONS_PAGE_SIZE) {+ hasMore = !consumedEntireBatch || candidates.length === GENERATIONS_PAGE_SIZE+ break+ }+ if (candidates.length < GENERATIONS_PAGE_SIZE) {+ break+ }+ }return {- generations: generationRows- .map((generation) => ({- ...generation,- aiInput: inputsByGenerationKey[generation.uuid] ?? generation.aiInput,- sentiment: sentimentByGenerationKey[generation.uuid] ?? null,- }))- .filter((generation) => generation.sentiment !== null),- rawCount: response?.results?.length ?? 0,+ generations,+ rawCount,+ hasMore,}}diff --git a/products/ai_observability/frontend/sentimentResults.ts b/products/ai_observability/frontend/sentimentResults.tsindex 4f65183f3844..ffc1961eb234 100644--- a/products/ai_observability/frontend/sentimentResults.ts+++ b/products/ai_observability/frontend/sentimentResults.ts@@ -7,6 +7,8 @@ export const GENERATION_SENTIMENT_SELECT = "'' -- Sentiment"const SENTIMENT_LABELS = new Set(['positive', 'neutral', 'negative'])+export function normalizeSentimentResult(value: Record<string, unknown>): GenerationSentiment+export function normalizeSentimentResult(value: unknown): GenerationSentiment | nullexport function normalizeSentimentResult(value: unknown): GenerationSentiment | null {if (!value || typeof value !== 'object') {return nulldiff --git a/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx b/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsxindex f884bfd7d1e6..19303ef1e60e 100644--- a/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx+++ b/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx@@ -306,6 +306,7 @@ export function AIObservabilitySentiment(): JSX.Element {return (<div data-attr="llma-sentiment-tab"><SentimentControls />+ <p className="text-sm text-muted mb-3">Results are ranked by their strongest positive or negative score.</p>{generationsLoading && generations.length === 0 ? (<div className="flex items-center justify-center py-20">@@ -320,6 +321,17 @@ export function AIObservabilitySentiment(): JSX.Element {<div className="text-center py-20 text-muted"><p className="text-lg font-medium mb-1">No sentiment evaluation results found</p><p className="text-sm">Try changing the date range or filters, or wait for matching generations.</p>+ {hasMore && (+ <LemonButton+ type="secondary"+ size="small"+ onClick={loadMoreGenerations}+ className="mt-4"+ data-attr="llma-sentiment-load-more"+ >+ Load more+ </LemonButton>+ )}</div>) : (<>diff --git a/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.test.ts b/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.test.tsindex ab73843e250b..fca80ca1d655 100644--- a/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.test.ts+++ b/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.test.ts@@ -1,5 +1,8 @@import { expectLogic } from 'kea-test-utils'+import { sceneLogic } from 'scenes/sceneLogic'+import { emptySceneParams } from 'scenes/scenes'+import { initKeaTests } from '~/test/init'import { evaluationsList } from '../generated/api'@@ -53,7 +56,7 @@ describe('aiObservabilitySentimentLogic', () => {beforeEach(() => {initKeaTests()mockEvaluationsList.mockResolvedValue({ count: 0, results: [] })- mockFetchSentimentGenerationsPage.mockResolvedValue({ generations: [], rawCount: 0 })+ mockFetchSentimentGenerationsPage.mockResolvedValue({ generations: [], rawCount: 0, hasMore: false })logic = nullavailabilityLogic = null})@@ -76,6 +79,7 @@ describe('aiObservabilitySentimentLogic', () => {mockFetchSentimentGenerationsPage.mockResolvedValue({generations: [generationWithSentiment],rawCount: 1,+ hasMore: false,})mountLogics()@@ -88,6 +92,22 @@ describe('aiObservabilitySentimentLogic', () => {expect(logic!.values.showSentimentEvaluationOnboarding).toBe(false)})+ it('does not automatically load another page when more results are available', async () => {+ mockFetchSentimentGenerationsPage.mockResolvedValue({+ generations: [generationWithSentiment],+ rawCount: 200,+ hasMore: true,+ })+ mountLogics()++ await expectLogic(logic!, () => {+ sceneLogic.actions.setScene('AIObservability', 'aiObservabilitySentiment', emptySceneParams)+ }).toFinishAllListeners()++ expect(mockFetchSentimentGenerationsPage).toHaveBeenCalledTimes(1)+ expect(logic!.values.hasMore).toBe(true)+ })+it('shows onboarding only when no configured eval and no stored sentiment rows match', async () => {mountLogics()diff --git a/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.tsindex b38824e572bd..12481a20735a 100644--- a/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts+++ b/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts@@ -11,7 +11,7 @@ import type { AnyPropertyFilter } from '../../../../frontend/src/types'import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'import type { AIObservabilityTabId } from '../aiObservabilitySharedLogic'import { sentimentEvaluationAvailabilityLogic } from '../sentimentEvaluationAvailabilityLogic'-import { fetchSentimentGenerationsPage, GENERATIONS_PAGE_SIZE, type SentimentGeneration } from '../sentimentQueries'+import { fetchSentimentGenerationsPage, type SentimentGeneration } from '../sentimentQueries'import type { MessageSentiment } from '../sentimentResults'import { extractContentText } from '../sentimentUtils'@@ -40,10 +40,6 @@ export interface GroupedSentimentCard {export type AIObservabilitySentimentLogicProps = Record<string, never>-/** Stop auto-loading once we have at least this many visible cards */-const MIN_VISIBLE_CARDS = 50-/** Cap how many extra pages we fetch automatically to avoid runaway API calls */-const MAX_AUTO_LOAD_ROUNDS = 3// Match backend MAX_MESSAGE_CHARS (2000) so training data captures the same text window the model classifiedexport const CLASSIFIER_WINDOW = 2000/** Number of other visible cards to sample as negative (impressed) examples per engagement */@@ -143,9 +139,7 @@ function captureEngagementEvents(}}-// Tracks the raw (pre-dedup) count from the last loadMoreGenerations fetch,-// so the listener can determine hasMore accurately despite deduplication.-let lastRawFetchCount = 0+let lastPageHasMore = falselet nextGenerationsOffset = 0// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -162,7 +156,6 @@ export interface aiObservabilitySentimentLogicValues {hasSentimentEvaluations: boolean // sentimentEvaluationAvailabilityLogicsentimentEvaluationsLoading: boolean // sentimentEvaluationAvailabilityLogicactiveFilters: Set<SentimentCategory>- autoLoadRounds: numberexpandedCardIds: Set<string>generations: SentimentGeneration[]generationsError: boolean@@ -262,8 +255,7 @@ export interface aiObservabilitySentimentLogicMeta {generations: SentimentGeneration[],generationsLoading: boolean,generationsError: boolean,- hasMore: boolean,- autoLoadRounds: number+ hasMore: boolean) => boolean}}@@ -353,13 +345,6 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyloadGenerations: () => true,},],- autoLoadRounds: [- 0 as number,- {- loadGenerations: () => 0,- loadMoreGenerations: (state: number) => state + 1,- },- ],hasLoadedOnce: [false as boolean,{@@ -382,14 +367,14 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTy{loadGenerations: async () => {const page = await fetchSentimentGenerationsPage(values, 0)- lastRawFetchCount = page.rawCount+ lastPageHasMore = page.hasMorenextGenerationsOffset = page.rawCountreturn page.generations},loadMoreGenerations: async () => {const existing = values.generationsconst page = await fetchSentimentGenerationsPage(values, nextGenerationsOffset)- lastRawFetchCount = page.rawCount+ lastPageHasMore = page.hasMorenextGenerationsOffset += page.rawCountconst existingGenerationIds = new Set(existing.map((g) => g.uuid))const unique = page.generations.filter((g) => !existingGenerationIds.has(g.uuid))@@ -518,7 +503,6 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTys.generationsLoading,s.generationsError,s.hasMore,- s.autoLoadRounds,],(hasLoadedSentimentEvaluations: boolean,@@ -527,8 +511,7 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTygenerations: SentimentGeneration[],generationsLoading: boolean,generationsError: boolean,- hasMore: boolean,- autoLoadRounds: number+ hasMore: boolean): boolean =>hasLoadedSentimentEvaluations &&hasLoadedOnce &&@@ -536,7 +519,7 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTy!generationsLoading &&!generationsError &&generations.length === 0 &&- (!hasMore || autoLoadRounds >= MAX_AUTO_LOAD_ROUNDS),+ !hasMore,],}),@@ -548,10 +531,10 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTy}},loadGenerationsSuccess: () => {- actions.setHasMore(lastRawFetchCount >= GENERATIONS_PAGE_SIZE)+ actions.setHasMore(lastPageHasMore)},loadMoreGenerationsSuccess: () => {- actions.setHasMore(lastRawFetchCount >= GENERATIONS_PAGE_SIZE)+ actions.setHasMore(lastPageHasMore)},toggleCardExpanded: ({ cardKey: key }) => {// Only track when expanding (key is now in the set), not collapsing@@ -610,15 +593,8 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyif (wasAnalyzing && !stillAnalyzing && values.activeTab === 'sentiment') {const totalGenerations = values.generations.lengthconst cardCount = values.sentimentCards.length- const visibleCards = values.groupedSentimentCards.length- // Auto-load more generations if we don't have enough visible cards- const shouldAutoLoad =- visibleCards < MIN_VISIBLE_CARDS &&- values.hasMore &&- values.autoLoadRounds < MAX_AUTO_LOAD_ROUNDS-- if ((totalGenerations === 0 || cardCount === 0) && !shouldAutoLoad) {+ if (totalGenerations === 0 || cardCount === 0) {posthog.capture('llma sentiment empty state', {reason: totalGenerations === 0 ? 'no_generations' : 'no_sentiment_results',total_generations: totalGenerations,@@ -626,10 +602,6 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyintensity_threshold: values.intensityThreshold,})}-- if (shouldAutoLoad) {- actions.loadMoreGenerations()- }}wasAnalyzing = stillAnalyzing},