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(insights): stop converting legacy filters on read (#96074)

Thomas Obermüllerf505bb17b803
diff --git a/frontend/src/exporter/ExportedInsight/ExportedInsight.tsx b/frontend/src/exporter/ExportedInsight/ExportedInsight.tsx
index 1035e0392ff1..dfc6b8ebe2ef 100644
--- a/frontend/src/exporter/ExportedInsight/ExportedInsight.tsx
+++ b/frontend/src/exporter/ExportedInsight/ExportedInsight.tsx
@@ -34,7 +34,7 @@ export function ExportedInsight({
}): JSX.Element {
useMountedLogic(dataThemeLogic({ themes }))
- const insight = getQueryBasedInsightModel(legacyInsight)
+ const insight = getQueryBasedInsightModel(legacyInsight, 'exported_insight')
// getQueryBasedInsightModel returns the caller's query object by reference — clone it so the
// export-only tweaks below (legend settings, table editing controls) can't leak into a shared model.
insight.query = insight.query ? structuredClone(insight.query) : insight.query
diff --git a/frontend/src/exporter/scenes/ExporterDashboardScene.tsx b/frontend/src/exporter/scenes/ExporterDashboardScene.tsx
index ae7a20ae6aa8..b1e90a83a0d2 100644
--- a/frontend/src/exporter/scenes/ExporterDashboardScene.tsx
+++ b/frontend/src/exporter/scenes/ExporterDashboardScene.tsx
@@ -59,7 +59,7 @@ export default function ExporterDashboardScene({
type: ExportedData['type']
themes: ExportedData['themes']
}): JSX.Element {
- const queryBasedDashboard = useMemo(() => getQueryBasedDashboard(dashboard)!, [dashboard])
+ const queryBasedDashboard = useMemo(() => getQueryBasedDashboard(dashboard, 'exported_dashboard')!, [dashboard])
return (
<>
{type !== ExportType.Image && (
diff --git a/frontend/src/models/dashboardsModel.tsx b/frontend/src/models/dashboardsModel.tsx
index 74bc7d7a48d4..33ad735569dd 100644
--- a/frontend/src/models/dashboardsModel.tsx
+++ b/frontend/src/models/dashboardsModel.tsx
@@ -430,7 +430,9 @@ export const dashboardsModel = kea<dashboardsModelType>([
count: 1,
next: null,
previous: null,
- results: [getQueryBasedDashboard(exportedDashboard) as DashboardBasicType],
+ results: [
+ getQueryBasedDashboard(exportedDashboard, 'dashboards_model') as DashboardBasicType,
+ ],
}
}
@@ -451,7 +453,9 @@ export const dashboardsModel = kea<dashboardsModelType>([
return {
...dashboards,
- results: dashboards.results?.map((dashboard) => getQueryBasedDashboard(dashboard)!),
+ results: dashboards.results?.map(
+ (dashboard) => getQueryBasedDashboard(dashboard, 'dashboards_model')!
+ ),
}
},
},
@@ -494,7 +498,7 @@ export const dashboardsModel = kea<dashboardsModelType>([
`api/environments/${teamLogic.values.currentTeamId}/dashboards/${id}`,
beforeChange
)
- actions.updateDashboardSuccess(getQueryBasedDashboard(reverted))
+ actions.updateDashboardSuccess(getQueryBasedDashboard(reverted, 'dashboards_model'))
lemonToast.success('Dashboard change reverted')
},
},
@@ -505,7 +509,7 @@ export const dashboardsModel = kea<dashboardsModelType>([
return null
}
- const mappedDashboard = getQueryBasedDashboard(response)
+ const mappedDashboard = getQueryBasedDashboard(response, 'dashboards_model')
if (!mappedDashboard) {
return mappedDashboard
}
@@ -517,7 +521,8 @@ export const dashboardsModel = kea<dashboardsModelType>([
await api.update(`api/environments/${teamLogic.values.currentTeamId}/dashboards/${id}`, {
deleted: true,
delete_insights: deleteInsights,
- })
+ }),
+ 'dashboards_model'
) as DashboardType<QueryBasedInsightModel>
deleteFromTree('dashboard', String(id))
return deleted
@@ -526,7 +531,8 @@ export const dashboardsModel = kea<dashboardsModelType>([
const restored = getQueryBasedDashboard(
await api.update(`api/environments/${teamLogic.values.currentTeamId}/dashboards/${id}`, {
deleted: false,
- })
+ }),
+ 'dashboards_model'
) as DashboardType<QueryBasedInsightModel>
refreshTreeItem('dashboard', String(id))
return restored
@@ -539,7 +545,7 @@ export const dashboardsModel = kea<dashboardsModelType>([
}
)
eventUsageLogic.actions.reportDashboardPinToggled(id, true, source)
- return getQueryBasedDashboard(response)!
+ return getQueryBasedDashboard(response, 'dashboards_model')!
},
unpinDashboard: async ({ id, source }) => {
const response = await api.update<DashboardType>(
@@ -549,7 +555,7 @@ export const dashboardsModel = kea<dashboardsModelType>([
}
)
eventUsageLogic.actions.reportDashboardPinToggled(id, false, source)
- return getQueryBasedDashboard(response)!
+ return getQueryBasedDashboard(response, 'dashboards_model')!
},
duplicateDashboard: async ({ id, name, show, duplicateTiles }) => {
const result = await api.create<DashboardType>(
@@ -563,7 +569,7 @@ export const dashboardsModel = kea<dashboardsModelType>([
if (show) {
router.actions.push(urls.dashboard(result.id))
}
- return getQueryBasedDashboard(result)!
+ return getQueryBasedDashboard(result, 'dashboards_model')!
},
},
})),
diff --git a/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts b/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts
index 51bbf408c0ea..4bb4e8f6906d 100644
--- a/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts
+++ b/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts
@@ -395,15 +395,16 @@ export const filtersToQueryNode = (
})
}
- if (!filters.insight) {
- throw new Error('filtersToQueryNode expects "insight"')
- }
- if (!isKeyOf(filters.insight, insightTypeToNodeKind)) {
- throw new Error(`insightTypeToNodeKind has no key ${filters.insight}`)
+ // A stored filter object can omit `insight`. The server's converter reads that as trends
+ // (`_insight_type` in filter_to_query.py), so this reads it the same way rather than throwing on
+ // a shape the server accepts.
+ const insightType = filters.insight ?? InsightType.TRENDS
+ if (!isKeyOf(insightType, insightTypeToNodeKind)) {
+ throw new Error(`insightTypeToNodeKind has no key ${insightType}`)
}
const query: InsightsQueryBase<AnalyticsQueryResponseBase> = {
- kind: insightTypeToNodeKind[filters.insight],
+ kind: insightTypeToNodeKind[insightType],
properties: cleanGlobalProperties(filters.properties),
filterTestAccounts: filters.filter_test_accounts,
}
diff --git a/frontend/src/queries/nodes/InsightViz/utils.test.ts b/frontend/src/queries/nodes/InsightViz/utils.test.ts
index d254d44d2cce..9de3b4b88b57 100644
--- a/frontend/src/queries/nodes/InsightViz/utils.test.ts
+++ b/frontend/src/queries/nodes/InsightViz/utils.test.ts
@@ -1,4 +1,5 @@
-import { InsightModel } from '~/types'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { InsightModel, InsightType } from '~/types'
import { extractValidationErrorCode, getQueryBasedInsightModel } from './utils'
@@ -55,4 +56,22 @@ describe('getQueryBasedInsightModel', () => {
const result = getQueryBasedInsightModel(input as Partial<InsightModel>)
expect(result.dashboards).toEqual(expected)
})
+
+ it.each([
+ ['converts stored filters when the insight has no query', InsightType.TRENDS],
+ ['reads a filter object with no insight type as trends', undefined],
+ ])('%s', (_name, insightType) => {
+ // Insights written before queries are served as `filters` with a null `query`, and this
+ // conversion is the only thing that renders them. A stored object can omit the type, which
+ // the server's converter also reads as trends.
+ const result = getQueryBasedInsightModel({
+ query: null,
+ filters: { insight: insightType, events: [{ id: '$pageview' }] },
+ } as Partial<InsightModel>)
+
+ expect(result.query).toMatchObject({
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.TrendsQuery },
+ })
+ })
})
diff --git a/frontend/src/queries/nodes/InsightViz/utils.ts b/frontend/src/queries/nodes/InsightViz/utils.ts
index cd10e9e8256a..0bae6d09690a 100644
--- a/frontend/src/queries/nodes/InsightViz/utils.ts
+++ b/frontend/src/queries/nodes/InsightViz/utils.ts
@@ -87,8 +87,16 @@ type ReturnInsightModel<T> = T extends InsightModel
? Partial<QueryBasedInsightModel>
: never
-/** Get an insight with `query` only. Eventual `filters` will be converted. */
-export function getQueryBasedInsightModel<T extends InputInsightModel>(insight: T): ReturnInsightModel<T> {
+/** Get an insight with `query` only. Eventual `filters` will be converted.
+ *
+ * `source` names the surface for the conversion telemetry. Pass one: without it the call is
+ * indistinguishable from every other caller, and the event cannot say which surfaces still rely on
+ * converting legacy filters in the browser.
+ */
+export function getQueryBasedInsightModel<T extends InputInsightModel>(
+ insight: T,
+ source?: string
+): ReturnInsightModel<T> {
const { filters, ...baseInsight } = insight
// The API is phasing out the deprecated `dashboards` field (already omitted for token
// callers, eventually for all); derive it from `dashboard_tiles` so remaining readers
@@ -98,22 +106,27 @@ export function getQueryBasedInsightModel<T extends InputInsightModel>(insight:
return {
...baseInsight,
...(dashboards ? { dashboards } : {}),
- query: getQueryFromInsightLike(insight),
+ query: getQueryFromInsightLike(insight, source),
} as unknown as ReturnInsightModel<T>
}
/** Get a `query` from an object that potentially has `filters` instead of a `query`. */
-export function getQueryFromInsightLike(insight: {
- query?: Node<Record<string, any>> | null
- filters?: Partial<FilterType>
-}): Node<Record<string, any>> | null {
+export function getQueryFromInsightLike(
+ insight: {
+ query?: Node<Record<string, any>> | null
+ filters?: Partial<FilterType>
+ },
+ source?: string
+): Node<Record<string, any>> | null {
let query
if (insight.query) {
query = insight.query
} else if (insight.filters && Object.keys(insight.filters).filter((k) => k != 'filter_test_accounts').length > 0) {
query = {
kind: NodeKind.InsightVizNode,
- source: filtersToQueryNode(insight.filters, { source: 'insight_viz_get_query_from_insight_like' }),
+ source: filtersToQueryNode(insight.filters, {
+ source: source ?? 'insight_viz_get_query_from_insight_like',
+ }),
} as InsightVizNode
} else {
query = null
@@ -175,7 +188,8 @@ export const getDefaultQuery = (
/** Get a dashboard where eventual `filters` based tiles are converted to `query` based ones. */
export const getQueryBasedDashboard = (
- dashboard: DashboardType<InsightModel> | DashboardType<QueryBasedInsightModel> | null
+ dashboard: DashboardType<InsightModel> | DashboardType<QueryBasedInsightModel> | null,
+ source?: string
): DashboardType<QueryBasedInsightModel> | null => {
if (dashboard == null) {
return null
@@ -187,7 +201,7 @@ export const getQueryBasedDashboard = (
(tile) =>
({
...tile,
- ...(tile.insight != null ? { insight: getQueryBasedInsightModel(tile.insight) } : {}),
+ ...(tile.insight != null ? { insight: getQueryBasedInsightModel(tile.insight, source) } : {}),
}) as DashboardTile<QueryBasedInsightModel>
),
}
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 57386d0c2ba1..6fc2b306e3d5 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -232,23 +232,26 @@ function mergeUpdatedWidgetTileIntoDashboard(
dashboard: DashboardType<QueryBasedInsightModel>,
updatedTile: DashboardTile<QueryBasedInsightModel>
): DashboardType<QueryBasedInsightModel> | null {
- return getQueryBasedDashboard({
- ...dashboard,
- tiles: dashboard.tiles.map((existingTile) => {
- if (existingTile.id !== updatedTile.id) {
- return existingTile
- }
+ return getQueryBasedDashboard(
+ {
+ ...dashboard,
+ tiles: dashboard.tiles.map((existingTile) => {
+ if (existingTile.id !== updatedTile.id) {
+ return existingTile
+ }
- return {
- ...existingTile,
- ...updatedTile,
- widget:
- existingTile.widget && updatedTile.widget
- ? { ...existingTile.widget, ...updatedTile.widget }
- : (updatedTile.widget ?? existingTile.widget),
- }
- }),
- } as DashboardType<InsightModel>)
+ return {
+ ...existingTile,
+ ...updatedTile,
+ widget:
+ existingTile.widget && updatedTile.widget
+ ? { ...existingTile.widget, ...updatedTile.widget }
+ : (updatedTile.widget ?? existingTile.widget),
+ }
+ }),
+ } as DashboardType<InsightModel>,
+ 'dashboard_scene'
+ )
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -1481,7 +1484,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
throw new Error('Dashboard response was empty or invalid')
}
- return getQueryBasedDashboard(dashboard)
+ return getQueryBasedDashboard(dashboard, 'dashboard_scene')
} catch (error: any) {
if (error.status === 404) {
return null
@@ -1510,7 +1513,10 @@ export const dashboardLogic = kea<dashboardLogicType>([
if (data.type === 'metadata') {
metadataReceived = true
actions.loadDashboardMetadataSuccess(
- getQueryBasedDashboard(data.dashboard as DashboardType<InsightModel>)
+ getQueryBasedDashboard(
+ data.dashboard as DashboardType<InsightModel>,
+ 'dashboard_scene'
+ )
)
} else if (data.type === 'tile') {
actions.receiveTileFromStream(data)
@@ -1629,7 +1635,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
cache.shouldRefreshTilesAfterSave = true
}
cache.dashboardChangesPersisted = true
- return getQueryBasedDashboard(updatedDashboard)
+ return getQueryBasedDashboard(updatedDashboard, 'dashboard_scene')
} catch (e) {
lemonToast.error('Could not update dashboard: ' + String(e))
return values.dashboard
@@ -1692,7 +1698,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
tiles: tilesToUpdate.length > 0 ? tilesToUpdate : undefined,
}
)
- return getQueryBasedDashboard(dashboard)
+ return getQueryBasedDashboard(dashboard, 'dashboard_scene')
} catch (e) {
// Re-throw so duplicateTileFailure fires. Swallowing the error resolved it as a
// success, so the tile refreshed with no copy and the user kept clicking.
@@ -1715,7 +1721,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
to_dashboard: toDashboard,
}
)
- return getQueryBasedDashboard(dashboard)
+ return getQueryBasedDashboard(dashboard, 'dashboard_scene')
},
copyToDashboard: async ({ tile, fromDashboard, toDashboard, toDashboardName }) => {
if (!tile?.insight && !tile?.text && !tile?.button_tile && !tile?.widget) {
@@ -2123,7 +2129,9 @@ export const dashboardLogic = kea<dashboardLogicType>([
const transformedTile = {
...tile,
- ...(tile.insight != null ? { insight: getQueryBasedInsightModel(tile.insight) } : {}),
+ ...(tile.insight != null
+ ? { insight: getQueryBasedInsightModel(tile.insight, 'dashboard_tile_stream') }
+ : {}),
}
let newTiles = [...state.tiles, transformedTile]
@@ -3511,7 +3519,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
tiles: [...tilesToUpdate, { id: newTile.id, layouts: newTileLayout }],
}
)
- const updated = getQueryBasedDashboard(response)
+ const updated = getQueryBasedDashboard(response, 'dashboard_scene')
if (updated) {
dashboardsModel.actions.updateDashboardSuccess(updated)
}
@@ -3866,7 +3874,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
values.dashboard?.customization?.layout_compaction ?? DashboardGridCompaction.Vertical,
}
)
- dashboardsModel.actions.updateDashboardSuccess(getQueryBasedDashboard(dashboard))
+ dashboardsModel.actions.updateDashboardSuccess(getQueryBasedDashboard(dashboard, 'dashboard_scene'))
eventUsageLogic.actions.reportDashboardTileDensityConfigured(tileSpacing)
} catch {
if (!cache.pendingDashboardTileSpacing) {
@@ -3908,7 +3916,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
grid_spacing: values.dashboard?.customization?.tile_spacing ?? 'standard',
}
)
- dashboardsModel.actions.updateDashboardSuccess(getQueryBasedDashboard(dashboard))
+ dashboardsModel.actions.updateDashboardSuccess(getQueryBasedDashboard(dashboard, 'dashboard_scene'))
} catch (error) {
posthog.captureException(error)
if (!cache.pendingDashboardGridCompaction) {
@@ -4302,10 +4310,13 @@ export const dashboardLogic = kea<dashboardLogicType>([
)
const createdTiles = findNewlyAddedWidgetTiles(previousWidgetTileIds, response.tiles)
if (createdTiles.length > 0 && values.dashboard?.id === dashboardId) {
- const dashboard = getQueryBasedDashboard({
- ...values.dashboard,
- tiles: [...values.dashboard.tiles, ...createdTiles],
- } as DashboardType<InsightModel>)
+ const dashboard = getQueryBasedDashboard(
+ {
+ ...values.dashboard,
+ tiles: [...values.dashboard.tiles, ...createdTiles],
+ } as DashboardType<InsightModel>,
+ 'dashboard_scene'
+ )
if (dashboard) {
dashboardsModel.actions.updateDashboardSuccess(dashboard)
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index d84711f56faf..ff35190c1bcc 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -310,7 +310,8 @@ export async function getInsightWithRetry(
})}`
const insightResponse: Response = await api.getResponse(apiUrl, methodOptions)
const legacyInsight: InsightModel | null = await getJSONOrNull(insightResponse)
- const result = legacyInsight !== null ? getQueryBasedInsightModel(legacyInsight) : null
+ const result =
+ legacyInsight !== null ? getQueryBasedInsightModel(legacyInsight, 'dashboard_tile_refresh') : null
if (result?.query_status?.error_message === RATE_LIMIT_ERROR_MESSAGE) {
attempt++
@@ -348,7 +349,10 @@ export async function getInsightWithRetry(
)
const legacyInsight: InsightModel | null = await getJSONOrNull(refreshedInsightResponse)
if (legacyInsight) {
- const queryBasedInsight = getQueryBasedInsightModel(legacyInsight)
+ const queryBasedInsight = getQueryBasedInsightModel(
+ legacyInsight,
+ 'dashboard_tile_refresh_async'
+ )
return { ...queryBasedInsight, query_status: finalStatus }
}
}
diff --git a/frontend/src/scenes/dashboard/newDashboardLogic.ts b/frontend/src/scenes/dashboard/newDashboardLogic.ts
index 59005f6f5022..f644bd69ae92 100644
--- a/frontend/src/scenes/dashboard/newDashboardLogic.ts
+++ b/frontend/src/scenes/dashboard/newDashboardLogic.ts
@@ -342,7 +342,7 @@ export const newDashboardLogic = kea<newDashboardLogicType>([
)
actions.hideNewDashboardModal()
actions.resetNewDashboard()
- const queryBasedDashboard = getQueryBasedDashboard(result)
+ const queryBasedDashboard = getQueryBasedDashboard(result, 'new_dashboard')
queryBasedDashboard && dashboardsModel.actions.addDashboardSuccess(queryBasedDashboard)
actions.submitNewDashboardSuccessWithResult(result)
tryShowMCPHint('dashboards.create', {
@@ -403,7 +403,7 @@ export const newDashboardLogic = kea<newDashboardLogicType>([
)
actions.resetNewDashboard()
- const queryBasedDashboard = getQueryBasedDashboard(result)
+ const queryBasedDashboard = getQueryBasedDashboard(result, 'new_dashboard')
queryBasedDashboard && dashboardsModel.actions.addDashboardSuccess(queryBasedDashboard)
actions.submitNewDashboardSuccessWithResult(result, variables)
diff --git a/frontend/src/scenes/dashboard/tileLayouts.ts b/frontend/src/scenes/dashboard/tileLayouts.ts
index f4db3073bb0a..f71603f688a2 100644
--- a/frontend/src/scenes/dashboard/tileLayouts.ts
+++ b/frontend/src/scenes/dashboard/tileLayouts.ts
@@ -248,7 +248,7 @@ export const calculateLayouts = (
}
const layouts = (sortedDashboardTiles || []).map((tile) => {
- const query = tile.insight ? getQueryBasedInsightModel(tile.insight) : null
+ const query = tile.insight ? getQueryBasedInsightModel(tile.insight, 'dashboard_tile_layout') : null
// Base constraints
let defaultW = 6
let defaultH = 5
diff --git a/frontend/src/scenes/data-management/events/eventInsightsLogic.ts b/frontend/src/scenes/data-management/events/eventInsightsLogic.ts
index 0a6e62013177..fe193686ec37 100644
--- a/frontend/src/scenes/data-management/events/eventInsightsLogic.ts
+++ b/frontend/src/scenes/data-management/events/eventInsightsLogic.ts
@@ -119,7 +119,9 @@ export const eventInsightsLogic = kea<eventInsightsLogicType>([
return {
...response,
filters,
- results: (response?.results ?? []).map((rawInsight: any) => getQueryBasedInsightModel(rawInsight)),
+ results: (response?.results ?? []).map((rawInsight: any) =>
+ getQueryBasedInsightModel(rawInsight, 'event_insights_list')
+ ),
} as InsightsResult
},
},
diff --git a/frontend/src/scenes/data-management/variables/insightsLoader.ts b/frontend/src/scenes/data-management/variables/insightsLoader.ts
index 820997aca1af..f7f83db9c752 100644
--- a/frontend/src/scenes/data-management/variables/insightsLoader.ts
+++ b/frontend/src/scenes/data-management/variables/insightsLoader.ts
@@ -34,7 +34,9 @@ export async function fetchInsightsUsingVariable(
`api/environments/${teamId}/insights/?basic=true&limit=${limit}&offset=${offset}`
)
- const insights = legacyResponse.results.map((legacyInsight) => getQueryBasedInsightModel(legacyInsight))
+ const insights = legacyResponse.results.map((legacyInsight) =>
+ getQueryBasedInsightModel(legacyInsight, 'variable_insights_list')
+ )
// Filter insights that use this variable
const filtered = insights.filter((insight) => insightUsesVariable(insight, variableId))
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
index 9941ef1c5120..96e24fdb0127 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
@@ -3252,7 +3252,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
const response = await api.get<PaginatedResponse<InsightModel>>(
`api/environments/${values.currentProjectId}/insights/?feature_flag=${values.featureFlag.key}&order=-created_at`
)
- return response.results.map((legacyInsight) => getQueryBasedInsightModel(legacyInsight))
+ return response.results.map((legacyInsight) =>
+ getQueryBasedInsightModel(legacyInsight, 'feature_flag_related_insights')
+ )
}
return []
},
diff --git a/frontend/src/scenes/insights/utils/api.ts b/frontend/src/scenes/insights/utils/api.ts
index cf5455095816..7de877d9bb54 100644
--- a/frontend/src/scenes/insights/utils/api.ts
+++ b/frontend/src/scenes/insights/utils/api.ts
@@ -11,7 +11,7 @@ async function _perform(
): Promise<QueryBasedInsightModel> {
const legacyInsight =
method === 'create' ? await api.insights[method](insight) : await api.insights[method](id!, insight)
- return getQueryBasedInsightModel(legacyInsight)
+ return getQueryBasedInsightModel(legacyInsight, 'insight_write')
}
export const insightsApi = {
@@ -36,14 +36,14 @@ export const insightsApi = {
return null
}
const legacyInsight = legacyInsights.results[0]
- return getQueryBasedInsightModel(legacyInsight) as QueryBasedInsightModel
+ return getQueryBasedInsightModel(legacyInsight, 'insight_scene_load') as QueryBasedInsightModel
},
async getByNumericId(numericId: number): Promise<QueryBasedInsightModel | null> {
const legacyInsight = await api.insights.get(numericId)
if (legacyInsight === null) {
return null
}
- return getQueryBasedInsightModel(legacyInsight)
+ return getQueryBasedInsightModel(legacyInsight, 'insight_load_by_numeric_id')
},
async create(insight: Partial<QueryBasedInsightModel>): Promise<QueryBasedInsightModel> {
return this._perform('create', insight)
diff --git a/frontend/src/scenes/project-homepage/projectHomepageLogic.tsx b/frontend/src/scenes/project-homepage/projectHomepageLogic.tsx
index 8a12bb1e18d9..d68d266aa408 100644
--- a/frontend/src/scenes/project-homepage/projectHomepageLogic.tsx
+++ b/frontend/src/scenes/project-homepage/projectHomepageLogic.tsx
@@ -106,7 +106,9 @@ export const projectHomepageLogic = kea<projectHomepageLogicType>([
const insights = await api.get<InsightModel[]>(
`api/environments/${values.currentProjectId}/insights/my_last_viewed`
)
- return insights.map((legacyInsight) => getQueryBasedInsightModel(legacyInsight))
+ return insights.map((legacyInsight) =>
+ getQueryBasedInsightModel(legacyInsight, 'project_homepage_recent_insights')
+ )
},
},
],
diff --git a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts
index e5e166698aef..fa527b5803f3 100644
--- a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts
+++ b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts
@@ -242,7 +242,9 @@ export const addSavedInsightsModalLogic = kea<addSavedInsightsModalLogicType>([
return {
...response,
- results: response.results.map((rawInsight: any) => getQueryBasedInsightModel(rawInsight)),
+ results: response.results.map((rawInsight: any) =>
+ getQueryBasedInsightModel(rawInsight, 'add_saved_insights_modal')
+ ),
}
},
},
diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
index 2f3defdcdebe..747ad8112f79 100644
--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
@@ -394,7 +394,9 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([
const response = {
...legacyResponse,
- results: legacyResponse.results.map((legacyInsight) => getQueryBasedInsightModel(legacyInsight)),
+ results: legacyResponse.results.map((legacyInsight) =>
+ getQueryBasedInsightModel(legacyInsight, 'saved_insights_list')
+ ),
}
if (filters.search && String(filters.search).match(/^[0-9]+$/)) {
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 9fdf582ace49..431c239b12b2 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -38,6 +38,7 @@ from posthog.models.quick_filter import QuickFilter
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.signals import mute_selected_signals
from posthog.test.db_context_capturing import capture_db_queries
+from posthog.test.insight_queries import browser_filtered_pageview_query, default_pageview_query, insight_query
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from posthog.user_permissions import UserPermissions
@@ -912,14 +913,11 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
def test_return_cached_results_bleh(self):
dashboard = Dashboard.objects.create(team=self.team, name="dashboard")
- filter_dict = {
- "events": [{"id": "$pageview"}],
- "properties": [{"key": "$browser", "value": "Mac OS X"}],
- }
+ query = browser_filtered_pageview_query()
- item = Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id="item11")
+ item = Insight.objects.create(query=query, team=self.team, short_id="item11")
DashboardTile.objects.create(dashboard=dashboard, insight=item)
- item2 = Insight.objects.create(filters=Filter(data=filter_dict).to_dict(), team=self.team, short_id="item22")
+ item2 = Insight.objects.create(query=query, team=self.team, short_id="item22")
DashboardTile.objects.create(dashboard=dashboard, insight=item2)
response = self.dashboard_api.get_dashboard(dashboard.pk, query_params={"refresh": False, "use_cache": True})
self.assertEqual(response["tiles"][0]["insight"]["result"], None)
@@ -1122,34 +1120,20 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
with freeze_time("2020-01-04T13:00:01Z"):
# Pretend we cached something a while ago, but we won't have anything in the redis cache
item_default: Insight = Insight.objects.create(
- filters=Filter(
- data={
- "events": [{"id": "$pageview"}],
- "properties": [{"key": "$browser", "value": "Mac OS X"}],
- }
- ).to_dict(),
+ query=browser_filtered_pageview_query(),
team=self.team,
order=0,
)
DashboardTile.objects.create(dashboard=dashboard, insight=item_default)
item_trends: Insight = Insight.objects.create(
- filters=Filter(
- data={
- "display": "ActionsLineGraph",
- "events": [
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "properties": [],
- }
- ],
- "filters": [],
+ query=insight_query(
+ {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview"}],
"interval": "day",
- "pagination": {},
- "session": "avg",
+ "trendsFilter": {"display": "ActionsLineGraph"},
}
- ).to_dict(),
+ ),
team=self.team,
order=1,
)
@@ -2111,7 +2095,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
self, _name: str, input_layouts: dict | None, expected_layouts: dict
) -> None:
dashboard = Dashboard.objects.create(team=self.team, name="test dashboard", created_by=self.user)
- insight = Insight.objects.create(filters={"name": "test"}, team=self.team, last_refresh=now())
+ insight = Insight.objects.create(query=default_pageview_query(), team=self.team, last_refresh=now())
original_tile = DashboardTile.objects.create(
dashboard=dashboard,
insight=insight,
@@ -2465,10 +2449,11 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
)
DashboardTile.objects.create(insight=item, dashboard=dashboard)
response = self.dashboard_api.get_dashboard(dashboard.pk)
- self.assertEqual(response["tiles"][0]["insight"]["filters"], {})
- query_source = response["tiles"][0]["insight"]["query"]["source"]
- self.assertEqual(query_source["kind"], "TrendsQuery")
- self.assertEqual(query_source["series"][0]["event"], "$pageview")
+ tile_insight = response["tiles"][0]["insight"]
+ self.assertIsNone(tile_insight["query"])
+ # The stored filters are the definition the client converts, so they have to survive the read.
+ self.assertEqual(tile_insight["filters"]["events"], [{"id": "$pageview"}])
+ self.assertNotIn("insight", tile_insight["filters"])
def test_retrieve_dashboard_different_team(self):
team2 = Team.objects.create(organization=Organization.objects.create(name="a"))
diff --git a/posthog/caching/calculate_results.py b/posthog/caching/calculate_results.py
index 823e3433fd78..cf21828c433a 100644
--- a/posthog/caching/calculate_results.py
+++ b/posthog/caching/calculate_results.py
@@ -14,11 +14,11 @@ from posthog.event_usage import AnalyticsProps
from posthog.hogql_queries.apply_dashboard_filters import resolve_effective_dashboard_filters
from posthog.hogql_queries.query_runner import get_query_runner_or_none, response_results_contain_models
from posthog.models import Team, User
-from posthog.schema_migrations.upgrade_manager import upgrade_query
+from posthog.schema_migrations.upgrade_manager import upgrade_insight
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
-from products.product_analytics.backend.facade.models import Insight, generate_insight_filters_hash
+from products.product_analytics.backend.facade.models import Insight
if TYPE_CHECKING:
from posthog.caching.insight_result import InsightResult
@@ -61,7 +61,7 @@ def calculate_cache_key(target: Union[DashboardTile, Insight]) -> Optional[str]:
dashboard: Optional[Dashboard] = target.dashboard if isinstance(target, DashboardTile) else None
if insight is not None:
- with upgrade_query(insight):
+ with upgrade_insight(insight):
if insight.query:
query_runner = get_query_runner_or_none(insight.query, insight.team)
if query_runner is None:
@@ -70,9 +70,6 @@ def calculate_cache_key(target: Union[DashboardTile, Insight]) -> Optional[str]:
query_runner.apply_dashboard_filters(DashboardFilter(**dashboard.filters))
return query_runner.get_cache_key()
- if insight.filters:
- return generate_insight_filters_hash(insight, dashboard)
-
return None
diff --git a/posthog/caching/warming.py b/posthog/caching/warming.py
index da9da631848d..139d7b8bce6f 100644
--- a/posthog/caching/warming.py
+++ b/posthog/caching/warming.py
@@ -26,7 +26,7 @@ from posthog.models import Team
from posthog.ph_client import ph_scoped_capture
from posthog.query_cache.freshness_index import clean_up_stale_insights, get_stale_insights
from posthog.query_creator_access import creator_access_revoked, report_creator_access_revoked
-from posthog.schema_migrations.upgrade_manager import upgrade_query
+from posthog.schema_migrations.upgrade_manager import upgrade_insight
from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
@@ -225,6 +225,10 @@ def warm_insight_cache_task(insight_id: int, dashboard_id: Optional[int]):
logger.info(f"Warming insight cache failed 404 insight not found: {insight_id}")
return
+ if insight.query is None:
+ logger.info(f"Warming insight cache skipped, insight has no query: {insight_id}")
+ return
+
dashboard = None
tag_queries(
@@ -237,7 +241,7 @@ def warm_insight_cache_task(insight_id: int, dashboard_id: Optional[int]):
tag_queries(dashboard_id=dashboard_id)
dashboard = insight.dashboards.filter(pk=dashboard_id).first()
- with upgrade_query(insight):
+ with upgrade_insight(insight):
logger.info(f"Warming insight cache: {insight.pk} for team {insight.team_id} and dashboard {dashboard_id}")
try:
diff --git a/posthog/hogql_queries/legacy_compatibility/flagged_conversion_manager.py b/posthog/hogql_queries/legacy_compatibility/flagged_conversion_manager.py
deleted file mode 100644
index 71fd95387c26..000000000000
--- a/posthog/hogql_queries/legacy_compatibility/flagged_conversion_manager.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from collections.abc import Iterator
-from contextlib import contextmanager
-from typing import TYPE_CHECKING
-
-from posthog.exceptions_capture import capture_exception
-
-from .filter_to_query import filter_to_query
-
-if TYPE_CHECKING:
- from products.product_analytics.backend.facade.models import Insight
-
-
-@contextmanager
-def conversion_to_query_based(insight: "Insight") -> Iterator[None]:
- """Convert the insight for HogQL-based calculation in place transparently, if conversion is needed."""
- if insight.query is None and insight.filters is not None:
- # TRICKY: We're making it so that a `filters`-based insights is converted to a `query`-based one
- # and treated as such
- try:
- insight.query = filter_to_query(insight.filters).model_dump()
- except Exception as e:
- capture_exception(e, additional_properties={"filter_to_query_todo": True})
- raise
-
- try:
- yield
- finally:
- # To prevent the sort-of-faked `query` from accidentally being saved to Postgres, we roll it back
- insight.query = None
- else:
- yield # No conversion to be done
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index d270c8e141df..a2aee91c4085 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -927,7 +927,6 @@
'last_refresh',
'objects',
'objects_including_soft_deleted',
- 'query_from_filters',
'refresh_attempt',
'refreshing',
'save',
diff --git a/posthog/schema_migrations/README.md b/posthog/schema_migrations/README.md
index 6c0cfc7c4973..3e0b79bfd137 100644
--- a/posthog/schema_migrations/README.md
+++ b/posthog/schema_migrations/README.md
@@ -7,7 +7,7 @@ Versioned migrations for the JSON query schema (`TrendsQuery`, `RetentionQuery`,
- Every query node has an optional `version` field. **A missing or `null` version means version 1.**
- A migration file (`NNNN_description.py`) declares `targets = {"<NodeKind>": <version>}` and a `transform(query: dict) -> dict` that converts a node from that version to the next. The version bump happens in the base class, not in `transform`.
- `upgrade(query)` (`upgrade.py`) walks a query dict recursively (any nesting: `InsightVizNode.source`, series arrays, ...) and replays migrations on every node whose `version` is below `LATEST_VERSIONS[kind]`.
-- `upgrade_query(insight)` (`upgrade_manager.py`) additionally converts legacy filters-based insights to query-based ones first. Note: it mutates `insight.query` in memory and does not restore it on exit.
+- `upgrade_insight(insight)` (`upgrade_manager.py`) upgrades an insight's stored query. Note: it mutates `insight.query` in memory and does not restore it on exit.
- Discovery (`__init__.py`) is lazy and validated: duplicate `(kind, version)` targets raise, and `validate.py` (exercised in CI by `test_validate.py::test_linear`) rejects gaps and non-linear versions.
## Where upgrades happen
@@ -16,7 +16,7 @@ Read/execute-time (always-on):
- `/api/.../query` and `process_query_dict` upgrade before pydantic validation.
- `POST /api/environments/:id/query/upgrade` is called by the frontend for untrusted queries (URL-embedded, notebook nodes).
-- Insight serializers upgrade on read; caching, alerts, exports, and subscriptions go through `upgrade_query`.
+- Insight serializers upgrade on read; caching, alerts, exports, and subscriptions go through `upgrade_insight`.
- Endpoints upgrade their immutable `EndpointVersion.query` snapshots at execution/materialization time; cohorts upgrade their saved `query` when compiling.
Write-time (backfill): a Temporal schedule (`upgrade-queries-schedule`, every 6 hours, see `posthog/temporal/product_analytics/`) rewrites stored **insights** whose queries are below the latest versions. Other stores (endpoint snapshots, notebook content, dashboard templates, cohort queries) are _not_ rewritten and rely on read-time upgrades forever.
diff --git a/posthog/schema_migrations/test/test_upgrade_manager.py b/posthog/schema_migrations/test/test_upgrade_manager.py
index e56976ec5393..0cd109176fac 100644
--- a/posthog/schema_migrations/test/test_upgrade_manager.py
+++ b/posthog/schema_migrations/test/test_upgrade_manager.py
@@ -1,5 +1,3 @@
-from typing import Any, Optional
-
import pytest
from unittest.mock import Mock
@@ -7,7 +5,7 @@ from posthog.schema import NodeKind
import posthog.schema_migrations as schema_migrations_module
from posthog.schema_migrations import LATEST_VERSIONS, MIGRATIONS, SchemaMigration
-from posthog.schema_migrations.upgrade_manager import upgrade_insight, upgrade_query
+from posthog.schema_migrations.upgrade_manager import upgrade_insight
class SampleMigration(SchemaMigration):
@@ -42,14 +40,3 @@ def test_upgrade_insight_context_manager():
with upgrade_insight(mock_insight):
assert mock_insight.query == upgraded_query
-
-
-def test_upgrade_query_manager():
- mock_insight = Mock()
- mock_insight.filters = {"aggregation_group_type_index": 2}
- mock_insight.query = None
-
- with upgrade_query(mock_insight):
- query: Optional[dict[str, Any]] = mock_insight.query
- assert query is not None
- assert query["aggregationGroupTypeIndex"] == 2
diff --git a/posthog/schema_migrations/upgrade_manager.py b/posthog/schema_migrations/upgrade_manager.py
index 37136ff3804d..7d951c99b6da 100644
--- a/posthog/schema_migrations/upgrade_manager.py
+++ b/posthog/schema_migrations/upgrade_manager.py
@@ -2,20 +2,12 @@ from collections.abc import Iterator
from contextlib import contextmanager
from typing import TYPE_CHECKING
-from posthog.hogql_queries.legacy_compatibility.flagged_conversion_manager import conversion_to_query_based
from posthog.schema_migrations.upgrade import upgrade
if TYPE_CHECKING:
from products.product_analytics.backend.facade.models import Insight
-@contextmanager
-def upgrade_query(insight: "Insight") -> Iterator[None]:
- """Replaces filters-based insights with query-based ones and upgrades the query to the latest version if needed."""
- with conversion_to_query_based(insight), upgrade_insight(insight):
- yield
-
-
@contextmanager
def upgrade_insight(insight: "Insight") -> Iterator[None]:
"""Upgrade the query to the latest version if needed."""
diff --git a/posthog/tasks/alerts/test/test_alert_evaluation.py b/posthog/tasks/alerts/test/test_alert_evaluation.py
index e11b141108c0..4d266afa1a59 100644
--- a/posthog/tasks/alerts/test/test_alert_evaluation.py
+++ b/posthog/tasks/alerts/test/test_alert_evaluation.py
@@ -87,24 +87,22 @@ class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):
assert AlertConfiguration.objects.get(pk=self.alert["id"]).state == AlertState.NOT_FIRING
- def test_alert_with_insight_with_filter(
+ def test_alert_cannot_be_pointed_at_an_insight_with_no_query(
self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
) -> None:
- # An alert still runs on an insight stored as filters, and only the ORM writes one now.
+ # Only the ORM writes a query-less insight now, and an alert on one has nothing to evaluate.
insight = Insight.objects.create(
team=self.team,
name="insight",
filters={"events": [{"id": "$pageview"}], "display": "BoldNumber"},
)
- self.client.patch(f"/api/projects/{self.team.id}/alerts/{self.alert['id']}", data={"insight": insight.id})
- self.set_thresholds(lower=1)
-
- run_alert_check(self.alert["id"])
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{self.alert['id']}", data={"insight": insight.id}
+ )
- assert mock_send_notifications_for_breaches.call_count == 1
- anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
- assert "The insight value ($pageview) for current interval (0) is less than lower threshold (1)" in anomalies
+ assert response.status_code == 400
+ assert AlertConfiguration.objects.get(pk=self.alert["id"]).insight_id != insight.id
def test_alert_triggered_for_single_formula(
self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
diff --git a/posthog/tasks/alerts/test/test_detector_breakdowns.py b/posthog/tasks/alerts/test/test_detector_breakdowns.py
index 28fd9bfcfea9..a7f905b36ff3 100644
--- a/posthog/tasks/alerts/test/test_detector_breakdowns.py
+++ b/posthog/tasks/alerts/test/test_detector_breakdowns.py
@@ -317,7 +317,7 @@ class TestCheckTrendsAlertWithDetectorBreakdowns:
class TestSimulateDetectorBreakdowns:
- @patch("products.alerts.backend.evaluation.detector.upgrade_query")
+ @patch("products.alerts.backend.evaluation.detector.upgrade_insight")
@patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")
def test_returns_breakdown_results(self, mock_calc: MagicMock, _mock_upgrade: MagicMock) -> None:
mock_calc.return_value = InsightResult(
@@ -349,7 +349,7 @@ class TestSimulateDetectorBreakdowns:
# Aggregated totals (each series has 1 point dropped for the incomplete current interval)
assert result["total_points"] == (len(STABLE_DATA) - 1) + (len(ANOMALOUS_DATA) - 1)
- @patch("products.alerts.backend.evaluation.detector.upgrade_query")
+ @patch("products.alerts.backend.evaluation.detector.upgrade_insight")
@patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")
def test_non_breakdown_has_no_breakdown_results(self, mock_calc: MagicMock, _mock_upgrade: MagicMock) -> None:
mock_calc.return_value = InsightResult(
@@ -375,7 +375,7 @@ class TestSimulateDetectorBreakdowns:
assert "breakdown_results" not in result
- @patch("products.alerts.backend.evaluation.detector.upgrade_query")
+ @patch("products.alerts.backend.evaluation.detector.upgrade_insight")
@patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")
def test_caps_breakdown_simulations(self, mock_calc: MagicMock, _mock_upgrade: MagicMock) -> None:
breakdown_results = [
@@ -404,7 +404,7 @@ class TestSimulateDetectorBreakdowns:
assert len(result["breakdown_results"]) == MAX_DETECTOR_BREAKDOWN_VALUES
- @patch("products.alerts.backend.evaluation.detector.upgrade_query")
+ @patch("products.alerts.backend.evaluation.detector.upgrade_insight")
@patch("products.alerts.backend.evaluation.hogql.calculate_for_query_based_insight")
def test_simulates_a_hogql_insight_through_the_registry(
self, mock_calc: MagicMock, _mock_upgrade: MagicMock
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index bd98b992ab10..7dfad7f8b715 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -18,7 +18,7 @@ from posthog.email import is_email_available
from posthog.errors import CH_TRANSIENT_ERRORS
from posthog.exceptions_capture import capture_exception
from posthog.query_creator_access import creator_access_revoked, report_creator_access_revoked
-from posthog.schema_migrations.upgrade_manager import upgrade_query
+from posthog.schema_migrations.upgrade_manager import upgrade_insight
from posthog.sync import database_sync_to_async
from posthog.tasks.alerts.investigation_notifications import run_investigation_notification_safety_net
from posthog.tasks.alerts.metrics_investigation import run_metrics_alert_investigation, should_investigate_metrics_alert
@@ -199,7 +199,7 @@ async def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResul
try:
insight = alert.insight
- with upgrade_query(insight):
+ with upgrade_insight(insight):
if insight.query is None:
raise ValueError("Alert's insight has no valid query")
threshold_config = alert.threshold.configuration if alert.threshold else None
diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.py
index 15a6200ec4ac..e4d581e7b5fe 100644
--- a/posthog/temporal/tests/test_subscriptions_workflows.py
+++ b/posthog/temporal/tests/test_subscriptions_workflows.py
@@ -33,6 +33,7 @@ from posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcome
from posthog.temporal.common.slo_interceptor import SloInterceptor
from posthog.temporal.exports.activities import export_asset_activity
from posthog.temporal.exports.types import ExportError
+from posthog.test.insight_queries import default_pageview_query
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
@@ -1108,7 +1109,11 @@ async def test_create_export_assets_creates_exported_assets(
team,
user,
):
- insight = await sync_to_async(Insight.objects.create)(team=team, short_id="prep01", name="Prep Test")
+ # The query is load-bearing: the query_service SLO assertion below only holds while the
+ # snapshot build has a query to run.
+ insight = await sync_to_async(Insight.objects.create)(
+ team=team, short_id="prep01", name="Prep Test", query=default_pageview_query()
+ )
subscription = await sync_to_async(create_subscription)(team=team, insight=insight, created_by=user)
env = ActivityEnvironment()
@@ -1386,7 +1391,11 @@ async def test_create_export_assets_dashboard_with_multiple_insights(
):
dashboard = await sync_to_async(Dashboard.objects.create)(team=team, name="Multi-insight", created_by=user)
for i in range(3):
- insight = await sync_to_async(Insight.objects.create)(team=team, short_id=f"prep{i:02d}", name=f"Insight {i}")
+ # The query is load-bearing: the query_service SLO assertion below only holds while the
+ # snapshot build has a query to run.
+ insight = await sync_to_async(Insight.objects.create)(
+ team=team, short_id=f"prep{i:02d}", name=f"Insight {i}", query=default_pageview_query()
+ )
await sync_to_async(DashboardTile.objects.create)(dashboard=dashboard, insight=insight)
subscription = await sync_to_async(create_subscription)(team=team, dashboard=dashboard, created_by=user)
diff --git a/posthog/test/insight_queries.py b/posthog/test/insight_queries.py
index 81264802368d..da7f6ac3f543 100644
--- a/posthog/test/insight_queries.py
+++ b/posthog/test/insight_queries.py
@@ -29,3 +29,13 @@ def default_pageview_query() -> dict[str, Any]:
"trendsFilter": {},
}
)
+
+
+def browser_filtered_pageview_query() -> dict[str, Any]:
+ return insight_query(
+ {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ "properties": [{"key": "$browser", "value": "Mac OS X", "type": "event"}],
+ }
+ )
diff --git a/products/alerts/backend/evaluation/detector.py b/products/alerts/backend/evaluation/detector.py
index af7912381baf..e9caf538fedb 100644
--- a/products/alerts/backend/evaluation/detector.py
+++ b/products/alerts/backend/evaluation/detector.py
@@ -10,7 +10,7 @@ from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.models.team import Team
from posthog.models.user import User
-from posthog.schema_migrations.upgrade_manager import upgrade_query
+from posthog.schema_migrations.upgrade_manager import upgrade_insight
# Low-level scoring/extraction primitives still live in the legacy detector module.
from posthog.tasks.alerts.detector import (
@@ -244,7 +244,7 @@ def simulate_detector_on_insight(
if insight.query is None:
raise ValueError("Insight has no valid query.")
- with upgrade_query(insight):
+ with upgrade_insight(insight):
query = insight.query
kind = get_from_dict_or_attr(query, "kind")
diff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.py
index 07dc0f43b523..9f4a0f3126f1 100644
--- a/products/alerts/backend/evaluation/dispatcher.py
+++ b/products/alerts/backend/evaluation/dispatcher.py
@@ -1,7 +1,7 @@
from posthog.schema import AlertCondition, InsightThreshold, IntervalType, NodeKind
from posthog.api.services.query import ExecutionMode
-from posthog.schema_migrations.upgrade_manager import upgrade_query
+from posthog.schema_migrations.upgrade_manager import upgrade_insight
from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResult
from posthog.utils import get_from_dict_or_attr
@@ -68,8 +68,10 @@ def check_alert_for_insight(alert: AlertConfiguration) -> AlertEvaluationResult:
``ExtractionResult`` and the comparator evaluates it against the threshold.
"""
insight = alert.insight
+ if insight.query is None:
+ raise ValueError("Alert's insight has no valid query")
- with upgrade_query(insight):
+ with upgrade_insight(insight):
query = insight.query
kind = get_from_dict_or_attr(query, "kind")
diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.py
index 5033eb7ee705..aed643e13d91 100644
--- a/products/alerts/backend/presentation/views/alert.py
+++ b/products/alerts/backend/presentation/views/alert.py
@@ -48,7 +48,7 @@ from posthog.models.tagged_item import TaggedItem
from posthog.permissions import get_authenticator_scopes
from posthog.rate_limit import AlertTestDeliveryThrottle
from posthog.resource_limits import LimitKey, check_count_limit
-from posthog.schema_migrations.upgrade_manager import upgrade_query
+from posthog.schema_migrations.upgrade_manager import upgrade_insight
from posthog.tasks.alerts.detector import MAX_DETECTOR_BREAKDOWN_VALUES
from posthog.tasks.alerts.schedule_restriction import validate_and_normalize_schedule_restriction
from posthog.tasks.alerts.utils import (
@@ -770,7 +770,7 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
# keep working when the flag is off.
_enforce_alert_feature_flags(self.context, insight)
_require_metrics_scope_for_programmatic_auth(self.context, insight)
- with upgrade_query(insight):
+ with upgrade_insight(insight):
query = insight.query
if query is None:
raise ValidationError({"insight": ["Insight has no valid query."]})
diff --git a/products/data_catalog/backend/logic/drift.py b/products/data_catalog/backend/logic/drift.py
index ad04b98a0a1c..576640761a56 100644
--- a/products/data_catalog/backend/logic/drift.py
+++ b/products/data_catalog/backend/logic/drift.py
@@ -24,11 +24,6 @@ def canonical_query_hash(query: dict) -> str:
return hashlib.sha256(json.dumps(upgrade(deepcopy(query)), sort_keys=True).encode()).hexdigest()
-def effective_insight_query(insight: Insight) -> Optional[dict]:
- """The insight's query, converting legacy ``filters``-only insights via query_from_filters."""
- return insight.query or insight.query_from_filters
-
-
def fetch_insight(team_id: int, short_id: str, *, include_deleted: bool = False) -> Optional[Insight]:
manager = Insight.objects_including_soft_deleted if include_deleted else Insight.objects
return manager.filter(team_id=team_id, short_id=short_id).first()
@@ -58,7 +53,7 @@ def compute_drift(metrics: Iterable[Metric]) -> dict[UUID, bool]:
if insight is None or insight.deleted:
result[metric.id] = True
continue
- current_query = effective_insight_query(insight)
+ current_query = insight.query
if not current_query:
result[metric.id] = True
continue
diff --git a/products/data_catalog/backend/logic/metrics.py b/products/data_catalog/backend/logic/metrics.py
index 701aabbd9479..26764a98e82b 100644
--- a/products/data_catalog/backend/logic/metrics.py
+++ b/products/data_catalog/backend/logic/metrics.py
@@ -39,7 +39,7 @@ from .analytics import (
METRIC_UPDATED_EVENT,
capture_metric_event,
)
-from .drift import canonical_query_hash, compute_drift, effective_insight_query, fetch_insight
+from .drift import canonical_query_hash, compute_drift, fetch_insight
from .exceptions import MetricDrifted, SourceInsightUnavailable
from .validation import validate_description, validate_metric_definition
@@ -111,11 +111,9 @@ def _snapshot_from_insight(team: Team, short_id: str, user: Optional[User]) -> t
if insight is None:
raise ValidationError({"source_insight_short_id": "Insight not found."})
_require_insight_viewer_access(insight, team, user)
- query = effective_insight_query(insight)
+ query = insight.query
if not query:
- raise ValidationError(
- {"source_insight_short_id": "Could not convert this insight's query. Define the metric manually."}
- )
+ raise ValidationError({"source_insight_short_id": "This insight has no query. Define the metric manually."})
return query, canonical_query_hash(query)
@@ -376,11 +374,9 @@ def refresh_metric_from_insight(metric: Metric, user: Optional[User], request: "
if insight is None or insight.deleted:
raise SourceInsightUnavailable()
_require_insight_viewer_access(insight, metric.team, user)
- query = effective_insight_query(insight)
+ query = insight.query
if not query:
- raise SourceInsightUnavailable(
- "Could not convert the source insight's query. Edit the definition or unlink."
- )
+ raise SourceInsightUnavailable("The source insight has no query. Edit the definition or unlink.")
canonical_def, referenced = _canonical_definition(query, metric.team, user)
new_hash = canonical_query_hash(query)
diff --git a/products/exports/backend/api/test/test_exports.py b/products/exports/backend/api/test/test_exports.py
index 7f565dd432cb..a9036a3f315b 100644
--- a/products/exports/backend/api/test/test_exports.py
+++ b/products/exports/backend/api/test/test_exports.py
@@ -36,6 +36,7 @@ from posthog.settings import (
)
from posthog.tasks import exporter
from posthog.temporal.session_replay.rasterize_recording.types import RASTERIZE_WORKFLOW_TIMEOUT
+from posthog.test.insight_queries import browser_filtered_pageview_query
from products.access_control.backend.models.access_control import AccessControl
from products.dashboards.backend.models.dashboard import Dashboard
@@ -137,7 +138,7 @@ class TestExports(APIBaseTest):
cls.dashboard = Dashboard.objects.create(team=cls.team, name="example dashboard", created_by=cls.user)
cls.insight = Insight.objects.create(
- filters=Filter(data=cls.insight_filter_dict).to_dict(),
+ query=browser_filtered_pageview_query(),
team=cls.team,
created_by=cls.user,
name="example insight",
diff --git a/products/exports/backend/tasks/image_exporter.py b/products/exports/backend/tasks/image_exporter.py
index 1f2736a4b990..a3c2f872ba53 100644
--- a/products/exports/backend/tasks/image_exporter.py
+++ b/products/exports/backend/tasks/image_exporter.py
@@ -24,11 +24,12 @@ from posthog.hogql.errors import TableAccessDeniedError
from posthog.api.services.query import process_query_dict
from posthog.caching.calculate_results import calculate_for_query_based_insight
+from posthog.caching.insight_result import InsightResult
from posthog.event_usage import AnalyticsProps, EventSource
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.query_creator_access import creator_access_revoked, report_creator_access_revoked
-from posthog.schema_migrations.upgrade_manager import upgrade_query
+from posthog.schema_migrations.upgrade_manager import upgrade_insight
from posthog.tasks.exporter import EXPORT_TIMER
from posthog.utils import absolute_uri
@@ -556,9 +557,10 @@ def export_image(
if tile:
tile_filters_override = tile.filters_overrides
+ result: InsightResult | None = None
if query_override:
# query_override is upgraded inside calculate_for_query_based_insight,
- # so we skip upgrade_query (which only upgrades insight.query we won't use).
+ # so we skip upgrade_insight (which only upgrades insight.query we won't use).
# variables_override is None because query_override already encodes the
# user's full current state — applying saved dashboard variables on top
# would clobber unsaved variable selections.
@@ -574,8 +576,17 @@ def export_image(
query_override=query_override,
analytics_props=export_analytics_props,
)
+ elif exported_asset.insight.query is None:
+ # Nothing to warm: the insight stores only legacy filters, which the render
+ # converts in the browser. Failing here would lose an export the browser can
+ # still produce, so the render just starts without a warm cache. The dashboard
+ # branch below skips such a tile for the same reason.
+ logger.info(
+ "export_image.skip_warming_insight_without_query",
+ insight_id=exported_asset.insight.id,
+ )
else:
- with upgrade_query(exported_asset.insight):
+ with upgrade_insight(exported_asset.insight):
result = calculate_for_query_based_insight(
exported_asset.insight,
team=exported_asset.team,
@@ -587,7 +598,7 @@ def export_image(
tile_filters_override=tile_filters_override,
analytics_props=export_analytics_props,
)
- if result.cache_key:
+ if result is not None and result.cache_key:
insight_cache_keys[exported_asset.insight.id] = result.cache_key
elif exported_asset.dashboard:
logger.info(
@@ -612,7 +623,7 @@ def export_image(
if not insight or not insight.query:
continue
- with upgrade_query(insight):
+ with upgrade_insight(insight):
result = calculate_for_query_based_insight(
insight,
team=exported_asset.team,
diff --git a/products/exports/backend/tasks/test/test_image_exporter.py b/products/exports/backend/tasks/test/test_image_exporter.py
index 674b8c40811e..7170f3aeaa1e 100644
--- a/products/exports/backend/tasks/test/test_image_exporter.py
+++ b/products/exports/backend/tasks/test/test_image_exporter.py
@@ -501,6 +501,28 @@ class TestImageExporter(APIBaseTest):
else:
assert call_kwargs["variables_override"] is None
+ @patch("products.exports.backend.tasks.image_exporter.calculate_for_query_based_insight")
+ def test_insight_export_without_a_query_skips_cache_warming(self, mock_calculate: Any, *args: Any) -> None:
+ # An insight that stores only legacy filters has no query to warm, and warming it would
+ # raise. The render converts the filters in the browser, so the export still produces one.
+ insight = Insight.objects.create(
+ team=self.team,
+ name="Legacy insight",
+ filters={"events": [{"id": "$pageview"}]},
+ )
+ exported_asset = ExportedAsset.objects.create(
+ team=self.team,
+ export_format=ExportedAsset.ExportFormat.PNG,
+ insight=insight,
+ )
+
+ with self.settings(OBJECT_STORAGE_ENABLED=False):
+ image_exporter.export_image(exported_asset)
+
+ assert mock_calculate.call_count == 0
+ exported_asset.refresh_from_db()
+ assert exported_asset.content == b"image_data"
+
@parameterized.expand(
[
(
diff --git a/products/exports/backend/temporal/subscriptions/insight_snapshot.py b/products/exports/backend/temporal/subscriptions/insight_snapshot.py
index 37eaac49fd18..cf0e6b10ec4d 100644
--- a/products/exports/backend/temporal/subscriptions/insight_snapshot.py
+++ b/products/exports/backend/temporal/subscriptions/insight_snapshot.py
@@ -129,8 +129,6 @@ def _resolve_effective_query_json(insight: Insight, dashboard: Dashboard | None)
query_json = insight.get_effective_query(dashboard=dashboard)
if query_json is None:
query_json = insight.query
- if query_json is None:
- query_json = insight.query_from_filters
return query_json
@@ -266,7 +264,7 @@ def build_insight_delivery_snapshot(
base["cache_key"] = None
base["query_error"] = {
"type": "missing_query",
- "message": "Insight has no query or convertible filters",
+ "message": "Insight has no query",
"human_readable_error": "This insight has no query to run.",
}
base["comparison_enabled"] = False
diff --git a/products/product_analytics/backend/models/insight.py b/products/product_analytics/backend/models/insight.py
index 5780a35f0c1b..e9789228c213 100644
--- a/products/product_analytics/backend/models/insight.py
+++ b/products/product_analytics/backend/models/insight.py
@@ -1,4 +1,3 @@
-from functools import cached_property
from typing import TYPE_CHECKING, Any, Optional
from django.contrib.postgres.fields import ArrayField
@@ -278,19 +277,6 @@ class Insight(RootTeamMixin, FileSystemSyncMixin, models.Model):
sharing_configurations = self.sharingconfiguration_set.all()
return sharing_configurations[0].enabled if sharing_configurations and sharing_configurations[0] else False
- @cached_property
- def query_from_filters(self):
- from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query
-
- try:
- return {
- "kind": "InsightVizNode",
- "source": filter_to_query(self.filters).model_dump(exclude_none=True),
- "full": True,
- }
- except Exception as e:
- capture_exception(e)
-
def dashboard_filters(
self, dashboard: Optional["Dashboard"] = None, dashboard_filters_override: Optional[dict] = None
):
@@ -419,9 +405,9 @@ class Insight(RootTeamMixin, FileSystemSyncMixin, models.Model):
def _unwrapped_query_kind(self) -> str | None:
"""Innermost query ``kind`` after unwrapping DataTable/DataVisualization/InsightVizNode
wrappers, or None if the insight has no query."""
- from posthog.schema_migrations.upgrade_manager import upgrade_query
+ from posthog.schema_migrations.upgrade_manager import upgrade_insight
- with upgrade_query(self):
+ with upgrade_insight(self):
query = self.query
if query is None:
return None
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index ddfc200bf14e..121edc618483 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -120,7 +120,7 @@ from posthog.rate_limit import (
from posthog.renderers import SafeJSONRenderer
from posthog.resource_limits import LimitKey, check_count_limit
from posthog.schema_migrations.upgrade import upgrade
-from posthog.schema_migrations.upgrade_manager import upgrade_query
+from posthog.schema_migrations.upgrade_manager import upgrade_insight
from posthog.settings import CAPTURE_TIME_TO_SEE_DATA, SITE_URL
from posthog.shared_link_user import SharedLinkUser
from posthog.user_permissions import UserPermissionsSerializerMixin
@@ -482,12 +482,11 @@ class InsightBasicSerializer(
else:
representation.pop("dashboards", None)
- if instance.query is not None or instance.query_from_filters is not None:
+ if instance.query is not None:
representation["filters"] = {}
- representation["query"] = instance.query or instance.query_from_filters
+ representation["query"] = instance.query
else:
- filters = instance.dashboard_filters()
- representation["filters"] = filters
+ representation["filters"] = instance.dashboard_filters()
# upgrade the query to the latest version
representation["query"] = upgrade(representation["query"])
@@ -1237,10 +1236,10 @@ class InsightSerializer(InsightBasicSerializer):
tile_filters_override_requested_by_client(request, dashboard_tile, is_shared=is_shared) if request else {}
)
- if instance.query is not None or instance.query_from_filters is not None:
+ if instance.query is not None:
# Upgrade before applying dashboard filters: the stored query may predate the current
# schema, and apply_dashboard_filters_to_dict validates against the latest one
- query = upgrade(instance.query or instance.query_from_filters)
+ query = upgrade(instance.query)
if (
dashboard is not None
or dashboard_filters_override is not None
@@ -1280,9 +1279,6 @@ class InsightSerializer(InsightBasicSerializer):
dashboard_variables_override=dashboard_variables_override,
)
- if "insight" not in representation["filters"] and not representation["query"]:
- representation["filters"]["insight"] = "TRENDS"
-
representation["filters_hash"] = self.insight_result(instance).cache_key
# Hide PII fields when hideExtraDetails from SharingConfiguration is enabled
@@ -1342,7 +1338,7 @@ class InsightSerializer(InsightBasicSerializer):
message="Expected cache key not found during export - falling back to normal calculation",
)
- with upgrade_query(insight):
+ with upgrade_insight(insight):
try:
is_shared = self.context.get("is_shared", False)
execution_mode, shared_cache_age_seconds = resolve_execution_mode(
@@ -2720,8 +2716,8 @@ When set, the specified dashboard's filters and date range override will be appl
# equivalent today because team_id == project_id, and asymmetric only under the deprecated
# multi-team-per-project path being removed. Same trade-off as the feature flag bulk endpoint.
saved_insights = Insight.objects.filter(team__project_id=self.team.project_id, saved=True)
- # Counted rather than silently dropped: these still carry the toggle through `filter_to_query`, so a run
- # that leaves them behind has to say so instead of reporting that nothing needed changing.
+ # Counted rather than silently dropped: the toggle lives in the query, so a run that leaves these
+ # behind has to say so instead of reporting that nothing needed changing.
legacy_count = saved_insights.filter(query__isnull=True).count()
totals = {"updated": 0, "unchanged": 0, "unsupported": 0, "skipped": 0, "legacy": legacy_count}
diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.py
index 2c7d60d3f029..e19e6c2faefd 100644
--- a/products/product_analytics/backend/tests/api/test_insight.py
+++ b/products/product_analytics/backend/tests/api/test_insight.py
@@ -677,17 +677,15 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
def test_get_insight_by_short_id(self) -> None:
- filter_dict = {"events": [{"id": "$pageview"}]}
-
Insight.objects.create(
- filters=Filter(data=filter_dict).to_dict(),
+ query=default_pageview_query(),
team=self.team,
short_id="12345678",
)
# We need at least one more insight to make sure we're not just getting the first one
Insight.objects.create(
- filters=Filter(data=filter_dict).to_dict(),
+ query=default_pageview_query(),
team=self.team,
short_id="not-that-one",
)
@@ -695,7 +693,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# Red herring: Should be ignored because it's not on the current team (even though the user has access)
new_team = Team.objects.create(organization=self.organization)
Insight.objects.create(
- filters=Filter(data=filter_dict).to_dict(),
+ query=default_pageview_query(),
team=new_team,
short_id="12345678",
)
@@ -707,6 +705,29 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response.json()["results"][0]["short_id"], "12345678")
self.assertEqual(response.json()["results"][0]["query"]["source"]["series"][0]["event"], "$pageview")
+ @parameterized.expand([("full", ""), ("basic", "&basic=true")])
+ def test_listing_an_insight_with_only_filters_serves_them(self, _name: str, query_string: str) -> None:
+ # `unique_users` is not a math value the query schema accepts, so this definition cannot be
+ # expressed as a query at all. Reading it used to raise out of the serializer and fail the
+ # whole list request.
+ stored_filters = {"events": [{"id": "$pageview", "math": "unique_users"}]}
+ Insight.objects.create(
+ team=self.team,
+ saved=True,
+ short_id="brokenfl",
+ filters=stored_filters,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/insights/?short_id=brokenfl{query_string}")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ result = response.json()["results"][0]
+ self.assertIsNone(result["query"])
+ # The stored definition survives the read, and the absent `insight` key is not filled in:
+ # the client's converter defaults it, the same way the server's converter does.
+ self.assertEqual(result["filters"]["events"], stored_filters["events"])
+ self.assertNotIn("insight", result["filters"])
+
@parameterized.expand(
[
("numeric_id", lambda insight: insight.id),
@@ -1886,126 +1907,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(source["funnelsFilter"]["layout"], "horizontal")
self.assertEqual(len(objects[0].short_id), 8)
- def test_insight_refreshing_legacy_conversion(self) -> None:
- dashboard_id, _ = self.dashboard_api.create_dashboard({"filters": {"date_from": "-14d"}})
-
- with freeze_time("2012-01-14T03:21:34.000Z"):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="1",
- properties={"prop": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="2",
- properties={"prop": "another_val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="2",
- properties={"prop": "val", "another": "never_return_this"},
- )
-
- with freeze_time("2012-01-15T04:01:34.000Z"):
- # Written through the ORM because the API no longer accepts legacy filters, while rows
- # stored before that still have to render through read-time conversion.
- insight = Insight.objects.create(
- team=self.team,
- filters={
- "events": [{"id": "$pageview"}],
- "properties": [
- {
- "key": "another",
- "value": "never_return_this",
- "operator": "is_not",
- }
- ],
- },
- )
- DashboardTile.objects.create(insight=insight, dashboard=Dashboard.objects.get(pk=dashboard_id))
- self.assertEqual(insight.last_refresh, None)
-
- response = self.client.get(f"/api/projects/{self.team.id}/insights/{insight.id}/?refresh=true").json()
- self.assertEqual(response["result"][0]["data"], [0, 0, 0, 0, 0, 0, 2, 0])
- self.assertEqual(response["last_refresh"], "2012-01-15T04:01:34Z")
- self.assertEqual(response["last_modified_at"], "2012-01-15T04:01:34Z")
-
- with freeze_time("2012-01-15T05:01:34.000Z"):
- _create_event(team=self.team, event="$pageview", distinct_id="1")
- response = self.client.get(f"/api/projects/{self.team.id}/insights/{response['id']}/?refresh=true").json()
- self.assertEqual(response["result"][0]["data"], [0, 0, 0, 0, 0, 0, 2, 1])
- self.assertEqual(response["last_refresh"], "2012-01-15T05:01:34Z")
- self.assertEqual(response["last_modified_at"], "2012-01-15T04:01:34Z") # did not change
-
- with freeze_time("2012-01-16T05:01:34.000Z"):
- # load it in the context of the dashboard, so has last 14 days as filter
- response = self.client.get(
- f"/api/projects/{self.team.id}/insights/{response['id']}/?refresh=true&from_dashboard={dashboard_id}"
- ).json()
- self.assertEqual(
- response["result"][0]["data"],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 2.0,
- 1.0,
- 0.0,
- ],
- )
- self.assertEqual(response["last_refresh"], "2012-01-16T05:01:34Z")
- self.assertEqual(response["last_modified_at"], "2012-01-15T04:01:34Z") # did not change
-
- with freeze_time("2012-01-25T05:01:34.000Z"):
- response = self.client.get(f"/api/projects/{self.team.id}/insights/{response['id']}/").json()
- self.assertEqual(response["last_refresh"], None)
- self.assertEqual(response["last_modified_at"], "2012-01-15T04:01:34Z") # did not change
-
- # Test property filter
-
- dashboard = Dashboard.objects.get(pk=dashboard_id)
- dashboard.filters = {
- "properties": [{"key": "prop", "value": "val"}],
- "date_from": "-14d",
- }
- dashboard.save()
- with freeze_time("2012-01-16T05:01:34.000Z"):
- response = self.client.get(
- f"/api/projects/{self.team.id}/insights/{response['id']}/?refresh=true&from_dashboard={dashboard_id}"
- ).json()
- self.assertEqual(
- response["result"][0]["data"],
- [
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 1.0,
- 0.0,
- 0.0,
- ],
- )
-
@parameterized.expand(
[
[ # Property group filter, which is what's actually used these days
@@ -4046,27 +3947,6 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
self.assertEqual(response_json["timezone"], "UTC")
- def test_insight_with_filters_via_hogql(self) -> None:
- filter_dict = {"insight": "LIFECYCLE", "events": [{"id": "$pageview"}]}
-
- insight = Insight.objects.create(
- filters=Filter(data=filter_dict).to_dict(),
- team=self.team,
- short_id="xyz123",
- )
-
- # fresh response
- response = self.client.get(f"/api/projects/{self.team.id}/insights/{insight.id}/?refresh=true")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["result"][0]["data"], [0, 0, 0, 0, 0, 0, 0, 0])
- self.assertFalse(response.json()["is_cached"])
-
- # cached response
- response = self.client.get(f"/api/projects/{self.team.id}/insights/{insight.id}/?refresh=false&use_cache=true")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["result"][0]["data"], [0, 0, 0, 0, 0, 0, 0, 0])
- self.assertTrue(response.json()["is_cached"])
-
def test_insight_returns_cached_hogql(self) -> None:
insight = Insight.objects.create(
query={