Skip to content

: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.

fix(aio): stop the AI event detection poll filing an issue per tick (#97743)

posthog[bot]5b42dcdeef0f
diff --git a/docs/published/handbook/engineering/conventions/frontend-coding.md b/docs/published/handbook/engineering/conventions/frontend-coding.md
index a5f2c74a48ab..65a40b8b2f8a 100644
--- a/docs/published/handbook/engineering/conventions/frontend-coding.md
+++ b/docs/published/handbook/engineering/conventions/frontend-coding.md
@@ -41,6 +41,7 @@ Hence the explicit separation between the data and view layers.
- Extract a shared component once the same shape appears in several places and the call sites read as content, not markup. Keep new generics next to the feature that uses them, and promote to `lib/` only when a second feature needs them. Don't build wrappers with a single consumer, and don't add boolean variant props so one caller can switch half the component off — that's two components.
- Interactive elements are real `<button>`/`<a>` elements (`LemonButton` renders one) — never `onClick` on a `<div>`.
- Loading, empty, and error are three different screens. Never show an empty state from data that hasn't resolved yet — branch on the loading state first.
+ - In `createSetupDetectionLogic`, return `null` when a setup check cannot answer. Like a thrown error, it preserves an existing setup status or shows the product scene if no answer exists yet. Return `unknown` when the scene itself should handle the result, such as showing an access-denied screen. Successful checks can still advance setup when data arrives.
- When renaming a feature, sweep code symbols completely — but analytics-facing strings (event names, property names and values, `data-attr` values) and persisted keys are a frozen API: leave them as-is, with a comment noting they're pinned.
- Scenes
- Our app is built of _scenes_, managed through a scene router in `sceneLogic`.
diff --git a/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.test.ts b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.test.ts
index 35d19c78601a..934e37928a67 100644
--- a/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.test.ts
+++ b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.test.ts
@@ -23,7 +23,7 @@ describe('createSetupDetectionLogic', () => {
})
function buildLogic(
- detect: jest.Mock<Promise<ProductSetupStatus>, []>,
+ detect: jest.Mock<Promise<ProductSetupStatus | null>, []>,
pollIntervalMs?: number
): ReturnType<ReturnType<typeof createSetupDetectionLogic>['build']> {
const logic = createSetupDetectionLogic({
@@ -37,15 +37,18 @@ describe('createSetupDetectionLogic', () => {
// The factory's whole job is feeding the scene gate: a status that never
// arrives strands every adopting product on the scene-level spinner.
- it.each([['has-data'], ['needs-setup'], ['waiting-for-data'], ['unknown']] as const)(
- 'pushes a detected %s into productSetupStatusLogic',
- async (status) => {
- const logic = buildLogic(jest.fn().mockResolvedValue(status))
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
- expect(productSetupStatusLogic({ productKey: ProductKey.LOGS }).values.status).toBe(status)
- }
- )
+ it.each([
+ ['has-data', 'has-data'],
+ ['needs-setup', 'needs-setup'],
+ ['waiting-for-data', 'waiting-for-data'],
+ ['unknown', 'unknown'],
+ [null, 'unknown'],
+ ] as const)('pushes an initial detection of %s into productSetupStatusLogic as %s', async (status, expected) => {
+ const logic = buildLogic(jest.fn().mockResolvedValue(status))
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(productSetupStatusLogic({ productKey: ProductKey.LOGS }).values.status).toBe(expected)
+ })
it('fails open to unknown when detection fails before any answer', async () => {
const logic = buildLogic(jest.fn().mockRejectedValue(new Error('network down')))
@@ -54,17 +57,25 @@ describe('createSetupDetectionLogic', () => {
expect(productSetupStatusLogic({ productKey: ProductKey.LOGS }).values.status).toBe('unknown')
})
- it('never downgrades an existing answer on a poll blip', async () => {
- const detect = jest
- .fn<Promise<ProductSetupStatus>, []>()
- .mockResolvedValueOnce('needs-setup')
- .mockRejectedValueOnce(new Error('blip'))
+ it.each([
+ ['rejects', 'needs-setup'],
+ ['returns null', 'needs-setup'],
+ ['returns unknown', 'unknown'],
+ ] as const)('handles a poll that %s after an existing answer', async (failure, expected) => {
+ const detect = jest.fn<Promise<ProductSetupStatus | null>, []>().mockResolvedValueOnce('needs-setup')
+ if (failure === 'rejects') {
+ detect.mockRejectedValueOnce(new Error('blip'))
+ } else if (failure === 'returns null') {
+ detect.mockResolvedValueOnce(null)
+ } else {
+ detect.mockResolvedValueOnce('unknown')
+ }
const logic = buildLogic(detect)
logic.mount()
await expectLogic(logic).toFinishAllListeners()
logic.actions.detectStatus()
await expectLogic(logic).toFinishAllListeners()
- expect(productSetupStatusLogic({ productKey: ProductKey.LOGS }).values.status).toBe('needs-setup')
+ expect(productSetupStatusLogic({ productKey: ProductKey.LOGS }).values.status).toBe(expected)
})
// `toFinishAllListeners` waits on real timers, so under fake timers flush
diff --git a/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts
index a3475bb1ae58..70f919e5610c 100644
--- a/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts
+++ b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts
@@ -19,11 +19,11 @@ export interface SetupDetectionLogicOptions {
path: string[]
/**
* Resolve the product's current setup status. Runs on mount and on every poll
- * tick. Return `unknown` for "cannot tell" (e.g. no access) - the gate fails
- * open. Throwing counts as a detection failure: the gate fails open if nothing
- * has answered yet, and a later blip never downgrades an existing answer.
+ * tick. Return `unknown` to show the scene (e.g. its access-denied screen).
+ * Return `null` when the check cannot answer. Like throwing, this fails the
+ * gate open if nothing has answered yet and preserves an existing answer.
*/
- detect: () => Promise<ProductSetupStatus>
+ detect: () => Promise<ProductSetupStatus | null>
/**
* Re-check cadence while the product has no data yet, so the empty state flips
* to the real scene on its own once events land. Polling stops for good on the
@@ -132,7 +132,7 @@ export function createSetupDetectionLogic(options: SetupDetectionLogicOptions):
loaders({
detectedStatus: {
__default: null as ProductSetupStatus | null,
- detectStatus: async (_: void, breakpoint: BreakPointFunction): Promise<ProductSetupStatus> => {
+ detectStatus: async (_: void, breakpoint: BreakPointFunction): Promise<ProductSetupStatus | null> => {
const status = await detect()
breakpoint()
return status
@@ -152,6 +152,9 @@ export function createSetupDetectionLogic(options: SetupDetectionLogicOptions):
),
detectStatusSuccess: ({ detectedStatus }) => {
if (!detectedStatus) {
+ if (values.setupStatus === 'loading') {
+ actions.setDetectedStatus('unknown')
+ }
return
}
actions.setDetectedStatus(detectedStatus)
diff --git a/products/ai_observability/frontend/aiObservabilitySharedLogic.test.ts b/products/ai_observability/frontend/aiObservabilitySharedLogic.test.ts
index c60ce439befe..ce7ad9654d1c 100644
--- a/products/ai_observability/frontend/aiObservabilitySharedLogic.test.ts
+++ b/products/ai_observability/frontend/aiObservabilitySharedLogic.test.ts
@@ -118,6 +118,7 @@ describe('aiObservabilitySharedLogic', () => {
it.each([
[true, 'has-data'],
[false, 'needs-setup'],
+ [null, 'unknown'],
])('pushes hasSentAiEvent=%s into productSetupStatusLogic as %s', async (hasEvents, expected) => {
mockHasRecentAIEvents.mockResolvedValue(hasEvents)
const logic = aiObservabilitySharedLogic()
@@ -137,16 +138,45 @@ describe('aiObservabilitySharedLogic', () => {
expect(productSetupStatusLogic({ productKey: ProductKey.AI_OBSERVABILITY }).values.status).toBe('unknown')
})
- it('a failing re-check never downgrades an existing answer', async () => {
+ it.each([
+ ['rejects', (): void => void mockHasRecentAIEvents.mockRejectedValue(new Error('query failed'))],
+ ['cannot answer', (): void => void mockHasRecentAIEvents.mockResolvedValue(null)],
+ ])('a re-check that %s never downgrades an existing answer', async (_, breakTheCheck) => {
mockHasRecentAIEvents.mockResolvedValue(true)
const logic = aiObservabilitySharedLogic()
logic.mount()
await expectLogic(logic).toFinishAllListeners()
- mockHasRecentAIEvents.mockRejectedValue(new Error('query failed'))
+ breakTheCheck()
logic.actions.loadAIEventDefinition()
await expectLogic(logic).toFinishAllListeners()
expect(productSetupStatusLogic({ productKey: ProductKey.AI_OBSERVABILITY }).values.status).toBe('has-data')
})
+
+ it('doubles the re-check delay while the check cannot answer, and restores it once it can', async () => {
+ mockHasRecentAIEvents.mockResolvedValue(null)
+ jest.useFakeTimers()
+ try {
+ const logic = aiObservabilitySharedLogic()
+ logic.mount()
+ // `toFinishAllListeners` waits on a real timer, so it never settles here.
+ await jest.advanceTimersByTimeAsync(0)
+ expect(mockHasRecentAIEvents).toHaveBeenCalledTimes(1)
+
+ await jest.advanceTimersByTimeAsync(20000)
+ expect(mockHasRecentAIEvents).toHaveBeenCalledTimes(1)
+ await jest.advanceTimersByTimeAsync(20000)
+ expect(mockHasRecentAIEvents).toHaveBeenCalledTimes(2)
+
+ mockHasRecentAIEvents.mockResolvedValue(false)
+ await jest.advanceTimersByTimeAsync(80000)
+ expect(mockHasRecentAIEvents).toHaveBeenCalledTimes(3)
+
+ await jest.advanceTimersByTimeAsync(20000)
+ expect(mockHasRecentAIEvents).toHaveBeenCalledTimes(4)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
})
describe('instrumentationVerdictApplies', () => {
diff --git a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
index 1b17f267f1b9..33c218751b3f 100644
--- a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts
@@ -79,6 +79,8 @@ export interface SortState {
// Cadence of the setup-detection re-check while the team has no AI events yet.
const SETUP_POLL_INTERVAL_MS = 20000
+// Ceiling for that cadence, because whatever stops the check answering does not clear in one tick.
+const SETUP_POLL_MAX_INTERVAL_MS = 5 * 60 * 1000
const INITIAL_DASHBOARD_DATE_FROM = '-7d' as string | null
const INITIAL_EVENTS_DATE_FROM = '-1h' as string | null
@@ -162,7 +164,7 @@ export interface aiObservabilitySharedLogicValues {
dateFrom: string | null
dateTo: string | null
}
- hasSentAiEvent: boolean | undefined
+ hasSentAiEvent: boolean | null | undefined
hasSentAiEventLoading: boolean
instrumentationVerdictApplies: (windowDays: number | null) => boolean
propertyFilters: AnyPropertyFilter[]
@@ -201,10 +203,10 @@ export interface aiObservabilitySharedLogicActions {
errorObject?: any
}
loadAIEventDefinitionSuccess: (
- hasSentAiEvent: boolean,
+ hasSentAiEvent: boolean | null,
payload?: any
) => {
- hasSentAiEvent: boolean
+ hasSentAiEvent: boolean | null
payload?: any
}
restoreSavedDashboardDates: (
@@ -414,8 +416,8 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
loaders(() => ({
hasSentAiEvent: {
- __default: undefined as boolean | undefined,
- loadAIEventDefinition: async (): Promise<boolean> => {
+ __default: undefined as boolean | null | undefined,
+ loadAIEventDefinition: async (): Promise<boolean | null> => {
return hasRecentAIEvents()
},
},
@@ -428,12 +430,24 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
}
},
loadAIEventDefinitionSuccess: ({ hasSentAiEvent }) => {
+ if (hasSentAiEvent === null) {
+ // The check says nothing about this team, so publish `unknown` only where nothing
+ // has answered yet. That fails the gate open without downgrading a real answer.
+ if (values.setupStatus === 'loading') {
+ actions.setDetectedStatus('unknown')
+ }
+ cache.setSetupPollInterval(Math.min(cache.setupPollIntervalMs * 2, SETUP_POLL_MAX_INTERVAL_MS))
+ return
+ }
// Feed the app-wide setup-status layer (drives the scene empty-state gate).
actions.setDetectedStatus(hasSentAiEvent ? 'has-data' : 'needs-setup')
if (hasSentAiEvent) {
cache.disposables.dispose('setupPoll')
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.IngestFirstLlmEvent)
+ return
}
+ // The check works again, so a user waiting on their first event gets the fast flip back.
+ cache.setSetupPollInterval(SETUP_POLL_INTERVAL_MS)
},
loadAIEventDefinitionFailure: () => {
// A failing detection query must not strand the empty-state gate on its
@@ -787,14 +801,27 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
}
}
- detectAIEventsIfProjectKnown()
// While the empty state (or its post-skip reminder banner) is up, re-check on a
// timer so the page flips to the real product on its own once events land.
// Disposed as soon as data is detected; paused automatically on hidden tabs.
- cache.disposables.add(() => {
- const id = window.setInterval(detectAIEventsIfProjectKnown, SETUP_POLL_INTERVAL_MS)
- return () => clearInterval(id)
- }, 'setupPoll')
+ const registerSetupPoll = (): void => {
+ cache.disposables.add(() => {
+ const id = window.setInterval(detectAIEventsIfProjectKnown, cache.setupPollIntervalMs)
+ return () => clearInterval(id)
+ }, 'setupPoll')
+ }
+ // A call at the interval already in force leaves the running timer alone.
+ cache.setupPollIntervalMs = SETUP_POLL_INTERVAL_MS
+ cache.setSetupPollInterval = (intervalMs: number): void => {
+ if (cache.setupPollIntervalMs === intervalMs) {
+ return
+ }
+ cache.setupPollIntervalMs = intervalMs
+ registerSetupPoll()
+ }
+
+ detectAIEventsIfProjectKnown()
+ registerSetupPoll()
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.TrackCosts)
const urlHasTestAccountsParam = 'filter_test_accounts' in router.values.searchParams
diff --git a/products/ai_observability/frontend/emptyState/clustersSetupLogic.test.ts b/products/ai_observability/frontend/emptyState/clustersSetupLogic.test.ts
index f45f70092606..05df9f2e560e 100644
--- a/products/ai_observability/frontend/emptyState/clustersSetupLogic.test.ts
+++ b/products/ai_observability/frontend/emptyState/clustersSetupLogic.test.ts
@@ -32,6 +32,7 @@ describe('clustersSetupLogic', () => {
[1, false, 'has-data'],
[0, true, 'waiting-for-data'],
[0, false, 'needs-setup'],
+ [0, null, 'unknown'],
])('pushes %i runs and AI events=%s as status %s', async (runRows, hasAIEvents, expected) => {
querySpy.mockResolvedValue({ results: Array.from({ length: runRows }, () => [1]) })
mockHasRecentAIEvents.mockResolvedValue(hasAIEvents)
@@ -40,4 +41,35 @@ describe('clustersSetupLogic', () => {
await expectLogic(logic).toFinishAllListeners()
expect(productSetupStatusLogic({ productKey: ProductKey.LLM_CLUSTERS }).values.status).toBe(expected)
})
+
+ it.each([
+ [false, 'needs-setup'],
+ [true, 'waiting-for-data'],
+ ] as const)(
+ 'preserves the setup screen through a failed check with AI events=%s (%s)',
+ async (hasAIEvents, expected) => {
+ querySpy.mockResolvedValue({ results: [] })
+ mockHasRecentAIEvents.mockResolvedValue(hasAIEvents)
+ const logic = clustersSetupLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ const setupStatus = productSetupStatusLogic({ productKey: ProductKey.LLM_CLUSTERS })
+ expect(setupStatus.values.status).toBe(expected)
+
+ mockHasRecentAIEvents.mockResolvedValue(null)
+ logic.actions.detectStatus()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(setupStatus.values.status).toBe(expected)
+
+ mockHasRecentAIEvents.mockResolvedValue(hasAIEvents)
+ logic.actions.detectStatus()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(setupStatus.values.status).toBe(expected)
+
+ querySpy.mockResolvedValue({ results: [[1]] })
+ logic.actions.detectStatus()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(setupStatus.values.status).toBe('has-data')
+ }
+ )
})
diff --git a/products/ai_observability/frontend/emptyState/clustersSetupLogic.ts b/products/ai_observability/frontend/emptyState/clustersSetupLogic.ts
index d3db27e84be9..9b083861f26e 100644
--- a/products/ai_observability/frontend/emptyState/clustersSetupLogic.ts
+++ b/products/ai_observability/frontend/emptyState/clustersSetupLogic.ts
@@ -27,7 +27,12 @@ export const clustersSetupLogic = createSetupDetectionLogic({
if ((response.results?.length ?? 0) > 0) {
return 'has-data'
}
- return (await hasRecentAIEvents()) ? 'waiting-for-data' : 'needs-setup'
+ const seenAiEvents = await hasRecentAIEvents()
+ if (seenAiEvents === null) {
+ // Preserve any existing setup screen while the check cannot answer.
+ return null
+ }
+ return seenAiEvents ? 'waiting-for-data' : 'needs-setup'
},
// Runs are emitted about once a day, so a slow poll is enough to flip the
// screen; the wizard flow is what needs the needs-setup → waiting flip.
diff --git a/products/ai_observability/frontend/utils/aiEvents.test.ts b/products/ai_observability/frontend/utils/aiEvents.test.ts
index 44337b06e1a8..7e3045e95c1c 100644
--- a/products/ai_observability/frontend/utils/aiEvents.test.ts
+++ b/products/ai_observability/frontend/utils/aiEvents.test.ts
@@ -189,6 +189,27 @@ describe('aiEventsUtils', () => {
expect(result).toBe(false)
})
+ // A rejection from either request files one error tracking issue per poll tick.
+ it.each([
+ [
+ 'the event definitions request fails',
+ (): void => {
+ jest.spyOn(api.eventDefinitions, 'list').mockRejectedValue(new Error('Failed to fetch'))
+ },
+ ],
+ [
+ 'the ClickHouse probe fails',
+ (): void => {
+ jest.spyOn(api.eventDefinitions, 'list').mockResolvedValue({ results: [], count: 0 } as any)
+ jest.spyOn(api, 'query').mockRejectedValue(new Error('Failed to fetch'))
+ },
+ ],
+ ])('answers null rather than rejecting when %s', async (_, arrange) => {
+ arrange()
+
+ await expect(hasRecentAIEvents()).resolves.toBeNull()
+ })
+
it('handles undefined results from ClickHouse gracefully', async () => {
useMocks({
get: {
diff --git a/products/ai_observability/frontend/utils/aiEvents.ts b/products/ai_observability/frontend/utils/aiEvents.ts
index a6394d370bde..c9d12527f4c5 100644
--- a/products/ai_observability/frontend/utils/aiEvents.ts
+++ b/products/ai_observability/frontend/utils/aiEvents.ts
@@ -15,13 +15,24 @@ const AI_STALE_EVENT_DAYS = 90
const AI_STALE_EVENT_SECONDS = AI_STALE_EVENT_DAYS * 24 * 60 * 60
/**
- * Checks if the team has sent any AI events.
- *
+ * Checks if the team has sent any AI events. Answers `null` when the check could not run.
+ */
+export async function hasRecentAIEvents(): Promise<boolean | null> {
+ try {
+ return await queryRecentAIEvents()
+ } catch {
+ // Callers re-run this on a timer, so rejecting files one error tracking issue per tick for
+ // as long as the tab stays open. `client_request_failure` already records both requests.
+ return null
+ }
+}
+
+/**
* Uses a two-tier approach:
* 1. Fast path: Check EventDefinition table (Postgres)
* 2. Fallback: Query ClickHouse directly for recent events (for new users)
*/
-export async function hasRecentAIEvents(): Promise<boolean> {
+async function queryRecentAIEvents(): Promise<boolean> {
// Fast path: check EventDefinition (works for most existing users)
const aiEventDefinitions = await api.eventDefinitions.list({
event_type: EventDefinitionType.Event,
@@ -54,13 +65,11 @@ let inFlightAiEventsCheck: Promise<boolean> | null = null
async function runAiEventsCheck(): Promise<boolean> {
try {
+ // An unanswerable check reads as "not seen yet"; the poll retries on its next tick.
if (await hasRecentAIEvents()) {
seenAiEvents = true
}
return seenAiEvents
- } catch {
- // A transient API failure reads as "not seen yet"; the poll retries on its next tick.
- return false
} finally {
inFlightAiEventsCheck = null
}