: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
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import { urls } from 'scenes/urls'
import { initKeaTests } from '~/test/init'
import * as api from '../generated/api'
import type { OfflineHistoryPageApi } from '../generated/api.schemas'
import { offlineExperimentsLogic } from './offlineExperimentsLogic'
import { overviewScorers, overviewHistory } from './offlineOverviewFixtures'
import { offlineOverviewTrendLogic } from './offlineOverviewTrendLogic'
jest.mock('../generated/api', () => ({
llmAnalyticsScoreDefinitionsRetrieve: jest.fn(),
aiObservabilityOfflineScorersHistoryList: jest.fn(),
aiObservabilityOfflineExperimentsList: jest.fn(),
}))
const props = {
teamId: 997,
scorerId: overviewScorers[0].id,
dateFrom: '2026-09-01T00:00:00Z',
dateTo: '2026-09-28T00:00:00Z',
refreshKey: 0,
}
const page: OfflineHistoryPageApi = {
results: overviewHistory(overviewScorers[0]),
count: 6,
next: null,
previous: null,
next_cursor: null,
}
const retrieve = jest.mocked(api.llmAnalyticsScoreDefinitionsRetrieve)
const history = jest.mocked(api.aiObservabilityOfflineScorersHistoryList)
function mountOverview(): ReturnType<typeof offlineExperimentsLogic.build> {
router.actions.push(urls.aiObservabilityOfflineEvaluations(), {
scores: props.scorerId,
date_from: 'all',
date_to: props.dateTo,
})
const logic = offlineExperimentsLogic({ teamId: props.teamId, userId: 1, timezone: 'UTC' })
logic.mount()
return logic
}
describe('offlineOverviewTrendLogic', () => {
beforeEach(() => {
initKeaTests()
jest.resetAllMocks()
retrieve.mockResolvedValue(overviewScorers[0])
history.mockResolvedValue(page)
jest.mocked(api.aiObservabilityOfflineExperimentsList).mockResolvedValue({
results: [],
count: 0,
next: null,
previous: null,
next_cursor: null,
})
})
it('does not query history for a remembered scorer that is no longer accessible', async () => {
retrieve.mockRejectedValueOnce(new Error('Not found'))
const unavailable = offlineOverviewTrendLogic(props)
unavailable.mount()
await expectLogic(unavailable).toFinishAllListeners()
expect(unavailable.values.trend).toBeNull()
expect(unavailable.values.trendError).toBe(true)
expect(history).not.toHaveBeenCalled()
const accessible = offlineOverviewTrendLogic({ ...props, scorerId: overviewScorers[1].id })
accessible.mount()
await expectLogic(accessible).toFinishAllListeners()
expect(accessible.values.trend?.page).toEqual(page)
expect(accessible.values.trendError).toBe(false)
})
it.each(['failed', 'successful'])(
'does not let an older %s history request replace a newer window or its shared bounds',
async (outcome) => {
const overviewLogic = mountOverview()
const trendProps = {
...props,
dateFrom: undefined,
overviewId: overviewLogic.key,
dateTo: overviewLogic.values.dateRange!.dateTo,
}
let finishOld: () => void = () => {}
let markRequestStarted: () => void = () => {}
const requestStarted = new Promise<void>((resolve) => {
markRequestStarted = resolve
})
history.mockImplementationOnce(() => {
markRequestStarted()
return new Promise((resolve, reject) => {
finishOld = () =>
outcome === 'failed'
? reject(new Error('An older date window failed'))
: resolve({
...page,
results: page.results.map((point) => ({
...point,
experiment: { ...point.experiment, started_at: '2020-01-01T00:00:00Z' },
})),
})
})
})
const logic = offlineOverviewTrendLogic(trendProps)
logic.mount()
await requestStarted
expect(overviewLogic.values.trendXDomain).toBeUndefined()
overviewLogic.actions.setFilters({ run_source: 'ci' })
expect(overviewLogic.values.trendXDomain).toBeUndefined()
offlineOverviewTrendLogic({
...trendProps,
filters: overviewLogic.values.trendFilters,
})
await expectLogic(logic).toDispatchActions(['loadOfflineOverviewTrendSuccess'])
finishOld()
await expectLogic(logic).toFinishAllListeners()
expect(history).toHaveBeenLastCalledWith(
'997',
props.scorerId,
expect.objectContaining({
date_from: undefined,
run_source: 'ci',
statuses: 'completed,uploading,failed',
})
)
expect(logic.values.trend?.page).toEqual(page)
expect(logic.values.trendError).toBe(false)
expect(logic.values.trendLoading).toBe(false)
expect(overviewLogic.values.trendXDomain).toEqual([
Math.min(...page.results.map(({ experiment }) => Date.parse(experiment.started_at))),
Date.parse(props.dateTo),
])
}
)
it('loads every version for the graph while navigating summaries independently, defaulting to the latest', async () => {
const overviewLogic = mountOverview()
const trendProps = {
...props,
dateFrom: undefined,
overviewId: overviewLogic.key,
dateTo: overviewLogic.values.dateRange!.dateTo,
}
const olderPoints = page.results.slice(0, 2).map((point) => ({
...point,
experiment: { ...point.experiment, started_at: '2026-08-01T00:00:00Z' },
summary: {
...point.summary,
mean: 0.25,
scorer: { ...point.summary.scorer, id: 'older-version', version: 1 },
},
}))
history
.mockResolvedValueOnce({ ...page, count: 8, next_cursor: 'older' })
.mockResolvedValueOnce({ results: olderPoints, count: 8, next: null, previous: null, next_cursor: null })
const logic = offlineOverviewTrendLogic(trendProps)
logic.mount()
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.points).toEqual([...page.results, ...olderPoints])
expect(logic.values.versionSummaries.map((summary) => summary.scorer.version)).toEqual([2, 1])
expect(logic.values.periodSummary?.scorer.version).toBe(2)
expect(logic.values.periodSummary?.mean).toBeCloseTo(0.851667)
logic.actions.selectVersion('older-version')
expect(logic.values.periodSummary?.scorer.version).toBe(1)
expect(logic.values.periodSummary?.mean).toBe(0.25)
expect(logic.values.points).toEqual([...page.results, ...olderPoints])
expect(history).toHaveBeenLastCalledWith('997', props.scorerId, expect.objectContaining({ cursor: 'older' }))
expect(overviewLogic.values.trendXDomain).toEqual([
Date.parse('2026-08-01T00:00:00Z'),
Date.parse(props.dateTo),
])
history.mockResolvedValueOnce({
results: page.results.slice(0, 1),
count: 1,
next: null,
previous: null,
next_cursor: null,
})
overviewLogic.actions.setFilters({ date_from: '2026-09-20T00:00:00Z' })
offlineOverviewTrendLogic({
...trendProps,
dateFrom: '2026-09-20T00:00:00Z',
})
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.versionSummaries.map((summary) => summary.scorer.version)).toEqual([2])
expect(logic.values.periodSummary?.scorer.version).toBe(2)
expect(logic.values.points).toEqual(page.results.slice(0, 1))
expect(logic.values.versionSummaries[0]?.experimentCount).toBe(1)
expect(logic.values.versionSummaries[0]?.mean).toBe(0.64)
})
it('bounds large histories and releases read slots for queued scorers', async () => {
history.mockImplementation(async (_teamId, scorerId, query) => {
const offset = Number(query?.cursor || 0)
return {
results: Array.from({ length: 100 }, (_, index) => ({
...page.results[0],
experiment: { ...page.results[0].experiment, id: `${scorerId}-${offset + index}` },
})),
count: 1000,
next: null,
previous: null,
next_cursor: String(offset + 100),
}
})
const logics = Array.from({ length: 4 }, (_, index) =>
offlineOverviewTrendLogic({ ...props, scorerId: `busy-scorer-${index}`, dateFrom: undefined })
)
logics.forEach((logic) => logic.mount())
await Promise.all(logics.map((logic) => expectLogic(logic).toFinishAllListeners()))
for (const logic of logics) {
expect(logic.values.trendLoading).toBe(false)
expect(logic.values.points).toHaveLength(500)
expect(logic.values.trend?.page).toMatchObject({ count: 1000, next_cursor: '500' })
}
})
it('reloads shared filters including tag-only changes within the same frozen date range', async () => {
const logic = offlineOverviewTrendLogic({ ...props, filters: { run_source: 'local' } })
logic.mount()
await expectLogic(logic).toFinishAllListeners()
const filters = {
run_source: 'ci',
created_by_is_null: true,
statuses: 'failed',
tags: '["quality"]',
tag_match: 'any' as const,
}
offlineOverviewTrendLogic({ ...props, filters })
await expectLogic(logic).toFinishAllListeners()
expect(history).toHaveBeenCalledTimes(2)
expect(history).toHaveBeenLastCalledWith('997', props.scorerId, {
...filters,
date_from: props.dateFrom,
date_to: props.dateTo,
limit: 100,
})
offlineOverviewTrendLogic({
...props,
filters: { ...filters, tags: '["quality","production"]', tag_match: 'all' },
})
await expectLogic(logic).toFinishAllListeners()
expect(history).toHaveBeenCalledTimes(3)
expect(history).toHaveBeenLastCalledWith(
'997',
props.scorerId,
expect.objectContaining({
tags: '["quality","production"]',
tag_match: 'all',
date_from: props.dateFrom,
date_to: props.dateTo,
})
)
})
})