: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(dashboards): align widget refresh with the five-minute interval (#106153)
Matt Puab862acccb3c8
diff --git a/frontend/src/scenes/dashboard/DashboardReloadAction.tsx b/frontend/src/scenes/dashboard/DashboardReloadAction.tsxindex bd2a85bb14ae..925f7b1a8975 100644--- a/frontend/src/scenes/dashboard/DashboardReloadAction.tsx+++ b/frontend/src/scenes/dashboard/DashboardReloadAction.tsx@@ -1,5 +1,4 @@import { useActions, useValues } from 'kea'-import { useEffect, useState } from 'react'import { IconCheck, IconX } from '@posthog/icons'import { IconRefresh } from '@posthog/icons'@@ -80,19 +79,6 @@ export function DashboardReloadAction(): JSX.Element {? `Next bulk refresh possible ${dayjs(nextAllowedDashboardRefresh).fromNow()}`: ''- // Force a re-render when nextAllowedDashboardRefresh is reached, since the blockRefresh- // selector uses now() which isn't reactive - it only recomputes on dependency changes- const [, setRenderTrigger] = useState(0)- useEffect(() => {- if (nextAllowedDashboardRefresh) {- const msUntilRefreshAllowed = dayjs(nextAllowedDashboardRefresh).diff(dayjs())- if (msUntilRefreshAllowed > 0) {- const timeoutId = setTimeout(() => setRenderTrigger((n) => n + 1), msUntilRefreshAllowed + 100)- return () => clearTimeout(timeoutId)- }- }- }, [nextAllowedDashboardRefresh])-const options = INTERVAL_OPTIONS.map((option) => {return {...option,diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.tsindex 8a3f3bab26e2..2f9942d7680c 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts@@ -2688,14 +2688,22 @@ describe('dashboardLogic', () => {}).toFinishAllListeners()}- const recentRefresh = now().subtract(4, 'minutes')- logic.actions.updateDashboardLastRefresh(recentRefresh)- expect(logic.values.blockRefresh).toBe(true)+ jest.useFakeTimers()+ try {+ const recentRefresh = now().subtract(4, 'minutes')+ logic.actions.updateDashboardLastRefresh(recentRefresh)+ expect(logic.values.blockRefresh).toBe(true)- const lastRefresh = now().subtract(6, 'minutes')- logic.actions.updateDashboardLastRefresh(lastRefresh)- expect(logic.values.nextAllowedDashboardRefresh?.isSame(lastRefresh.add(5, 'minutes'))).toBe(true)- expect(logic.values.blockRefresh).toBe(false)+ await jest.advanceTimersByTimeAsync(60_100)+ expect(logic.values.blockRefresh).toBe(false)++ const lastRefresh = now().subtract(6, 'minutes')+ logic.actions.updateDashboardLastRefresh(lastRefresh)+ expect(logic.values.nextAllowedDashboardRefresh?.isSame(lastRefresh.add(5, 'minutes'))).toBe(true)+ expect(logic.values.blockRefresh).toBe(false)+ } finally {+ jest.useRealTimers()+ }})it('manual refresh reloads all insights', async () => {@@ -4037,6 +4045,20 @@ describe('dashboardLogic', () => {describe('widget orchestration', () => {let fetchRunWidgetsMock: jest.SpiedFunction<typeof widgetFetchUtils.fetchRunWidgets>+ async function makeInsightTilesFresh(): Promise<void> {+ for (const tile of logic.values.insightTiles) {+ if (tile.insight) {+ await expectLogic(logic, () => {+ dashboardsModel.actions.updateDashboardInsight(+ { ...tile.insight!, last_refresh: now().toISOString(), query: tile.insight!.query ?? null },+ undefined,+ 5+ )+ }).toFinishAllListeners()+ }+ }+ }+beforeEach(() => {featureFlagLogic.mount()featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.DASHBOARD_WIDGETS], {@@ -4065,6 +4087,28 @@ describe('dashboardLogic', () => {fetchRunWidgetsMock.mockRestore()})+ it('a stale widget releases the shared refresh block', async () => {+ logic = dashboardLogic({ id: 5 })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ await makeInsightTilesFresh()++ const currentTime = Date.now()+ jest.useFakeTimers()+ try {+ jest.setSystemTime(currentTime - 4 * 60_000)+ logic.actions.setWidgetRefreshStatuses([WIDGET_TILE.id], false)+ await jest.advanceTimersByTimeAsync(4 * 60_000)+ logic.actions.updateDashboardLastRefresh(dayjs())+ expect(logic.values.blockRefresh).toBe(true)++ await jest.advanceTimersByTimeAsync(60_100)+ expect(logic.values.blockRefresh).toBe(false)+ } finally {+ jest.useRealTimers()+ }+ })+it('refreshDashboardWidgets fetches run_widgets for widget tiles', async () => {logic = dashboardLogic({ id: 5 })logic.mount()@@ -4126,7 +4170,11 @@ describe('dashboardLogic', () => {logic = dashboardLogic({ id: 5 })logic.mount()await expectLogic(logic).toFinishAllListeners()+ await makeInsightTilesFresh()+ const previousFetchedAt = logic.values.widgetRefreshStatus[WIDGET_TILE.id]?.fetchedAt+ logic.actions.updateDashboardLastRefresh(dayjs())+ expect(logic.values.blockRefresh).toBe(true)fetchRunWidgetsMock.mockRejectedValueOnce(new Error('Network error'))await expectLogic(logic, () => {@@ -4134,6 +4182,8 @@ describe('dashboardLogic', () => {}).toFinishAllListeners()expect(logic.values.widgetRefreshStatus[WIDGET_TILE.id]?.error).toBe(DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE)+ expect(logic.values.widgetRefreshStatus[WIDGET_TILE.id]?.fetchedAt).toBe(previousFetchedAt)+ expect(logic.values.blockRefresh).toBe(true)})it('refreshDashboardWidgets sets friendly error when run_widgets returns per-tile error', async () => {@@ -4141,6 +4191,7 @@ describe('dashboardLogic', () => {logic.mount()await expectLogic(logic).toFinishAllListeners()+ const previousFetchedAt = logic.values.widgetRefreshStatus[WIDGET_TILE.id]?.fetchedAtfetchRunWidgetsMock.mockResolvedValueOnce([{tile_id: WIDGET_TILE.id,@@ -4156,6 +4207,7 @@ describe('dashboardLogic', () => {expect(logic.values.widgetRefreshStatus[WIDGET_TILE.id]?.error).toBe(DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE)expect(logic.values.widgetResultsByTileId[WIDGET_TILE.id]?.error).toBe('Query timeout')+ expect(logic.values.widgetRefreshStatus[WIDGET_TILE.id]?.fetchedAt).toBe(previousFetchedAt)})it('refreshDashboardWidgets only marks failed tiles when a chunk has mixed results', async () => {diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex bc6640025d91..0d6e2d55d44b 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -18,6 +18,7 @@ import type { BreakPointFunction } from 'kea'import { loaders } from 'kea-loaders'import { actionToUrl, beforeUnload, router, urlToAction } from 'kea-router'import { CombinedLocation } from 'kea-router/lib/utils'+import { subscriptions } from 'kea-subscriptions'import uniqBy from 'lodash.uniqby'import posthog from 'posthog-js'import { ResponsiveLayouts } from 'react-grid-layout'@@ -55,6 +56,7 @@ import {chunkTileIds,fetchRunWidgets,findNewlyAddedWidgetTiles,+ isWidgetStale,WIDGET_CLIENT_TTL_MS,} from 'scenes/dashboard/widgetFetchUtils'import { createDashboardWidgetTileRefreshScheduler } from 'scenes/dashboard/widgetTileRefreshScheduler'@@ -359,6 +361,7 @@ export interface dashboardLogicValues {loadingPreview: booleanmaxContext: MaxContextInput[]nextAllowedDashboardRefresh: Dayjs | null+ nextWidgetStaleAt: number | nulloldestRefreshed: Dayjs | nullpageVisibility: booleanpendingInsertion: PendingInsertion | null@@ -366,6 +369,7 @@ export interface dashboardLogicValues {placement: DashboardPlacementpreviewedDashboardSettings: DashboardSettings | nullprojectTreeRef: ProjectTreeRef+ refreshEligibilityTick: numberrefreshMetrics: {completed: numbertotal: number@@ -660,6 +664,9 @@ export interface dashboardLogicActions {order: numbertile: any}+ recheckRefreshEligibility: () => {+ value: true+ }refreshDashboardItem: (payload: { tile: DashboardTile }) => {tile: DashboardTile}@@ -1208,9 +1215,32 @@ export interface dashboardLogicMeta {oldestRefreshed: (sortedDates: Dayjs[], pageVisibility: boolean) => Dayjs | nulleffectiveLastRefresh: (lastDashboardRefresh: Dayjs | null, oldestRefreshed: Dayjs | null) => Dayjs | nullnextAllowedDashboardRefresh: (lastDashboardRefresh: Dayjs | null) => Dayjs | null+ nextWidgetStaleAt: (+ widgetTiles: DashboardTile[],+ widgetRefreshStatus: Record<+ number,+ {+ error?: string | null+ fetchedAt?: number+ loading?: boolean+ }+ >,+ dashboardWidgetsEnabled: boolean+ ) => number | nullblockRefresh: (nextAllowedDashboardRefresh: Dayjs | null,effectiveLastRefresh: Dayjs | null,+ widgetTiles: DashboardTile[],+ widgetRefreshStatus: Record<+ number,+ {+ error?: string | null+ fetchedAt?: number+ loading?: boolean+ }+ >,+ refreshEligibilityTick: number,+ dashboardWidgetsEnabled: boolean,placement: DashboardPlacement,pageVisibility: boolean) => boolean@@ -1441,6 +1471,7 @@ export const dashboardLogic = kea<dashboardLogicType>([saveLayout: true,resetUrlFilters: () => true,resetUrlVariables: true,+ recheckRefreshEligibility: true,setInitialVariablesLoaded: (initialVariablesLoaded: boolean) => ({ initialVariablesLoaded }),updateDashboardLastRefresh: (lastDashboardRefresh: Dayjs) => ({ lastDashboardRefresh }),overrideVariableValue: (variableId: string, value: any, isNull: boolean) => ({@@ -2573,20 +2604,30 @@ export const dashboardLogic = kea<dashboardLogicType>([tileIds.map((tileId) => [tileId,loading- ? { loading: true, error: null }- : { loading: false, error: error ?? null, fetchedAt: Date.now() },+ ? { ...state[tileId], loading: true, error: null }+ : {+ ...state[tileId],+ loading: false,+ error: error ?? null,+ fetchedAt: error ? state[tileId]?.fetchedAt : Date.now(),+ },])),}),setWidgetRunResults: (state, { results }) => {const next = { ...state }for (const tileId of Object.keys(results).map(Number)) {- next[tileId] = { ...next[tileId], loading: false, fetchedAt: Date.now() }+ next[tileId] = {+ ...next[tileId],+ loading: false,+ fetchedAt: results[tileId].error ? next[tileId]?.fetchedAt : Date.now(),+ }}return next},},],+ refreshEligibilityTick: [0, { recheckRefreshEligibility: (state) => state + 1 }],addWidgetTileLoading: [false,{@@ -3086,16 +3127,68 @@ export const dashboardLogic = kea<dashboardLogicType>([return lastDashboardRefresh.add(DASHBOARD_MIN_REFRESH_INTERVAL_MINUTES, 'minutes')},],+ nextWidgetStaleAt: [+ (s) => [s.widgetTiles, s.widgetRefreshStatus, s.dashboardWidgetsEnabled],+ (+ widgetTiles: DashboardTile[],+ widgetRefreshStatus: Record<+ number,+ {+ error?: string | null+ fetchedAt?: number+ loading?: boolean+ }+ >,+ dashboardWidgetsEnabled: boolean+ ): number | null => {+ if (!dashboardWidgetsEnabled) {+ return null+ }+ const deadlines = widgetTiles+ .map((tile) => {+ const status = widgetRefreshStatus[tile.id]+ return status?.fetchedAt && !status.error && !status.loading+ ? status.fetchedAt + WIDGET_CLIENT_TTL_MS+ : null+ })+ .filter((deadline): deadline is number => deadline !== null && deadline > Date.now())+ return deadlines.length ? Math.min(...deadlines) : null+ },+ ],blockRefresh: [// page visibility is only here to trigger a recompute when the page is hidden/shown- (s) => [s.nextAllowedDashboardRefresh, s.effectiveLastRefresh, s.placement, s.pageVisibility],- (nextAllowedDashboardRefresh: Dayjs, effectiveLastRefresh: Dayjs | null, placement: DashboardPlacement) => {+ (s) => [+ s.nextAllowedDashboardRefresh,+ s.effectiveLastRefresh,+ s.widgetTiles,+ s.widgetRefreshStatus,+ s.refreshEligibilityTick,+ s.dashboardWidgetsEnabled,+ s.placement,+ s.pageVisibility,+ ],+ (+ nextAllowedDashboardRefresh: Dayjs,+ effectiveLastRefresh: Dayjs | null,+ widgetTiles: DashboardTile[],+ widgetRefreshStatus: Record<number, { loading?: boolean; error?: string | null; fetchedAt?: number }>,+ _refreshEligibilityTick: number,+ dashboardWidgetsEnabled: boolean,+ placement: DashboardPlacement+ ) => {return (!(placement === DashboardPlacement.FeatureFlag) &&!(placement === DashboardPlacement.Group) &&!!nextAllowedDashboardRefresh &&nextAllowedDashboardRefresh?.isAfter(now()) &&- !isEffectiveRefreshStale(effectiveLastRefresh)+ !isEffectiveRefreshStale(effectiveLastRefresh) &&+ !(+ dashboardWidgetsEnabled &&+ widgetTiles.some((tile) => {+ const status = widgetRefreshStatus[tile.id]+ return !status?.error && isWidgetStale(status)+ })+ ))},],@@ -3351,6 +3444,28 @@ export const dashboardLogic = kea<dashboardLogicType>([},],})),+ subscriptions(({ actions, cache }) => ({+ nextAllowedDashboardRefresh: (deadline: Dayjs | null) => {+ cache.disposables.dispose('dashboardRefreshTimer')+ if (!deadline || !deadline.isAfter(now())) {+ return+ }+ cache.disposables.add(() => {+ const timerId = setTimeout(actions.recheckRefreshEligibility, Math.max(0, deadline.diff(now())) + 100)+ return () => clearTimeout(timerId)+ }, 'dashboardRefreshTimer')+ },+ nextWidgetStaleAt: (deadline: number | null) => {+ cache.disposables.dispose('widgetFreshnessTimer')+ if (!deadline) {+ return+ }+ cache.disposables.add(() => {+ const timerId = setTimeout(actions.recheckRefreshEligibility, Math.max(0, deadline - Date.now()) + 100)+ return () => clearTimeout(timerId)+ }, 'widgetFreshnessTimer')+ },+ })),events(({ actions, props, values, cache }) => ({afterMount: () => {// NOTE: initial dashboard load is done after variables are loaded in initialVariablesLoaded@@ -4268,7 +4383,11 @@ export const dashboardLogic = kea<dashboardLogicType>([return true}const fetchedAt = values.widgetRefreshStatus[tileId]?.fetchedAt- return !fetchedAt || Date.now() - fetchedAt > WIDGET_CLIENT_TTL_MS+ return (+ !!values.widgetRefreshStatus[tileId]?.error ||+ !fetchedAt ||+ Date.now() - fetchedAt >= WIDGET_CLIENT_TTL_MS+ )})if (staleTileIds.length === 0) {diff --git a/frontend/src/scenes/dashboard/widgetFetchUtils.test.ts b/frontend/src/scenes/dashboard/widgetFetchUtils.test.tsindex 0c0519d96b1d..a9597ad98f30 100644--- a/frontend/src/scenes/dashboard/widgetFetchUtils.test.ts+++ b/frontend/src/scenes/dashboard/widgetFetchUtils.test.ts@@ -1,8 +1,14 @@import type { DashboardTile } from '~/types'-import { chunkTileIds, findNewlyAddedWidgetTiles } from './widgetFetchUtils'+import { chunkTileIds, findNewlyAddedWidgetTiles, isWidgetStale } from './widgetFetchUtils'describe('widgetFetchUtils', () => {+ it('treats failed widgets as stale but not loading or missing widgets', () => {+ expect(isWidgetStale(undefined, 1_000_000)).toBe(false)+ expect(isWidgetStale({ error: 'Query failed', fetchedAt: 1_000_000 }, 1_000_000)).toBe(true)+ expect(isWidgetStale({ loading: true, fetchedAt: 1_000_000 }, 1_000_000)).toBe(false)+ })+const widgetTile = (id: number): DashboardTile => ({id,widget: { id: String(id), widget_type: 'error_tracking_list', config: {} },diff --git a/frontend/src/scenes/dashboard/widgetFetchUtils.ts b/frontend/src/scenes/dashboard/widgetFetchUtils.tsindex f571e3f5ea5d..2a4ad92d4509 100644--- a/frontend/src/scenes/dashboard/widgetFetchUtils.ts+++ b/frontend/src/scenes/dashboard/widgetFetchUtils.ts@@ -3,7 +3,19 @@ import type { DashboardWidgetRunResultApi } from '@posthog/products-dashboards/fimport type { DashboardTile } from '~/types'-export const WIDGET_CLIENT_TTL_MS = 15 * 60 * 1000+import { DASHBOARD_MIN_REFRESH_INTERVAL_MINUTES } from './dashboardUtils'++export const WIDGET_CLIENT_TTL_MS = DASHBOARD_MIN_REFRESH_INTERVAL_MINUTES * 60 * 1000++export function isWidgetStale(+ status: { loading?: boolean; error?: string | null; fetchedAt?: number } | undefined,+ currentTime = Date.now()+): boolean {+ return (+ !status?.loading &&+ (!!status?.error || (!!status?.fetchedAt && currentTime - status.fetchedAt >= WIDGET_CLIENT_TTL_MS))+ )+}export function findNewlyAddedWidgetTiles(previousTileIds: ReadonlySet<number>,