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.

feat(web-analytics): keep saved filter presets warm (#85995)

Lucas Ricoy614529b01425
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 56ffee10088c..c19b5e21ab62 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -39662,6 +39662,10 @@
"description": "Name of the query, preferably unique. For example web_analytics_vitals",
"type": "string"
},
+ "presetId": {
+ "description": "Short id of the saved Web analytics filter preset this query was run under, if any.",
+ "type": "string"
+ },
"productKey": {
"description": "Product responsible for this query. Use string, there's no need to churn the Schema when we add a new product *",
"type": "string"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index ded27f116ed0..2719be91ecfc 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -488,6 +488,8 @@ export interface QueryLogTags {
productKey?: string
/** Name of the query, preferably unique. For example web_analytics_vitals */
name?: string
+ /** Short id of the saved Web analytics filter preset this query was run under, if any. */
+ presetId?: string
}
/** @internal - no need to emit to schema.json. */
diff --git a/frontend/src/scenes/insights/utils/queryUtils.test.ts b/frontend/src/scenes/insights/utils/queryUtils.test.ts
index 06d896e07ffd..b8f7ed03da46 100644
--- a/frontend/src/scenes/insights/utils/queryUtils.test.ts
+++ b/frontend/src/scenes/insights/utils/queryUtils.test.ts
@@ -3,6 +3,7 @@ import { Node, NodeKind, TrendsFilter, TrendsQuery } from '~/queries/schema/sche
import { InsightType } from '~/types'
import {
+ compareDataNodeQuery,
compareQuery,
filterVariablesReferencedInQuery,
hasInvalidRegexFilter,
@@ -288,3 +289,31 @@ describe('isDraftQueryWorthSaving', () => {
expect(isDraftQueryWorthSaving(query, false)).toBe(expected)
})
})
+
+describe('compareDataNodeQuery', () => {
+ // Query log tags never change what the backend returns (it strips them from the cache
+ // payload), so a tag-only difference must not count as a changed query. Web analytics
+ // stamps the applied filter preset's id into tags, and treating that as a change would
+ // refetch every tile the moment someone saves a preset.
+ it.each([
+ [
+ 'an insight query node',
+ { kind: NodeKind.TrendsQuery, series: [] } as Node,
+ { kind: NodeKind.TrendsQuery, series: [], tags: { presetId: 'abc123' } } as Node,
+ ],
+ [
+ 'a non-insight node',
+ { kind: NodeKind.HogQLQuery, query: 'select 1' } as Node,
+ { kind: NodeKind.HogQLQuery, query: 'select 1', tags: { presetId: 'abc123' } } as Node,
+ ],
+ ])('ignores tags on %s', (_name, untagged, tagged) => {
+ expect(compareDataNodeQuery(untagged, tagged)).toBe(true)
+ })
+
+ it('reports a change against an undefined previous query instead of throwing', () => {
+ // dataNodeLogic passes oldProps.query, which is undefined on the first props change; a
+ // throw here crashed propsChanged before loadData and left tables permanently empty.
+ const query = { kind: NodeKind.HogQLQuery, query: 'select 1' } as Node
+ expect(compareDataNodeQuery(query, undefined as unknown as Node)).toBe(false)
+ })
+})
diff --git a/frontend/src/scenes/insights/utils/queryUtils.ts b/frontend/src/scenes/insights/utils/queryUtils.ts
index 3c6db4836342..faa66dcac093 100644
--- a/frontend/src/scenes/insights/utils/queryUtils.ts
+++ b/frontend/src/scenes/insights/utils/queryUtils.ts
@@ -139,13 +139,30 @@ export const haveVariablesOrFiltersChanged = (a: Node, b: Node): boolean => {
return false
}
+/** Query log metadata, stripped from result caching on the backend too, so it can never change what
+ * comes back. Comparing it would refetch every tile whenever a tag alone changes. */
+const withoutQueryLogTags = <T extends Node>(node: T): T => {
+ // dataNodeLogic compares against oldProps.query, which is undefined on the first props change.
+ if (!node || typeof node !== 'object' || !('tags' in node)) {
+ return node
+ }
+ const { tags: _tags, ...rest } = node as T & { tags?: unknown }
+ return rest as T
+}
+
/** Compares two queries for semantic equality to prevent double-fetching of data. */
export const compareDataNodeQuery = (a: Node, b: Node, opts?: CompareQueryOpts): boolean => {
if (isInsightQueryNode(a) && isInsightQueryNode(b)) {
- return objectsEqual(cleanInsightQuery(a, opts), cleanInsightQuery(b, opts))
+ return objectsEqual(
+ cleanInsightQuery(withoutQueryLogTags(a), opts),
+ cleanInsightQuery(withoutQueryLogTags(b), opts)
+ )
}
- return objectsEqual(objectCleanWithEmpty(a as any), objectCleanWithEmpty(b as any))
+ return objectsEqual(
+ objectCleanWithEmpty(withoutQueryLogTags(a) as any),
+ objectCleanWithEmpty(withoutQueryLogTags(b) as any)
+ )
}
/**
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
index df0588540741..088c6bce9e52 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
@@ -50,6 +50,7 @@ import { WebAnalyticsHealthCheck } from 'scenes/web-analytics/WebAnalyticsHealth
import { webAnalyticsLoadTimeLogic } from 'scenes/web-analytics/webAnalyticsLoadTimeLogic'
import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'
import { WebAnalyticsModal } from 'scenes/web-analytics/WebAnalyticsModal'
+import { WebAnalyticsSavePresetNudge } from 'scenes/web-analytics/WebAnalyticsSavePresetNudge'
import { WebAnalyticsShareColleagueBanner } from 'scenes/web-analytics/WebAnalyticsShareColleagueBanner'
import { WebTileHeader } from 'scenes/web-analytics/WebTileHeader'
import { useWebTileOpenInsight, useWebTileOverflowMenuItems } from 'scenes/web-analytics/webTileHeaderHooks'
@@ -877,6 +878,7 @@ export const WebAnalyticsDashboard = (): JSX.Element => {
<Filters tabs={<></>} />
<WebAnalyticsShareColleagueBanner />
+ <WebAnalyticsSavePresetNudge />
<ShareNudgePrompt />
<WebAnalyticsHealthCheck />
<MainContent />
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsSavePresetNudge.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsSavePresetNudge.tsx
new file mode 100644
index 000000000000..9b957df9f70a
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsSavePresetNudge.tsx
@@ -0,0 +1,41 @@
+import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { ProductTab } from './common'
+import { webAnalyticsFilterPresetsLogic } from './webAnalyticsFilterPresetsLogic'
+import { webAnalyticsLogic } from './webAnalyticsLogic'
+
+export function WebAnalyticsSavePresetNudge(): JSX.Element | null {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { productTab, hasNonDefaultFilters, appliedPresetShortId } = useValues(webAnalyticsLogic)
+ const { openSaveModal } = useActions(webAnalyticsFilterPresetsLogic)
+
+ if (
+ !featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_FILTERS_V2] ||
+ productTab !== ProductTab.ANALYTICS ||
+ !hasNonDefaultFilters ||
+ appliedPresetShortId
+ ) {
+ return null
+ }
+
+ return (
+ <LemonBanner
+ type="info"
+ dismissKey="web-analytics-save-preset-nudge"
+ action={{
+ children: 'Save as preset',
+ onClick: () => {
+ posthog.capture('web analytics save preset nudge clicked')
+ openSaveModal()
+ },
+ }}
+ >
+ Save these filters as a preset so you can come back to them in one click.
+ </LemonBanner>
+ )
+}
diff --git a/frontend/src/scenes/web-analytics/common.test.ts b/frontend/src/scenes/web-analytics/common.test.ts
index 8145c9fc4cb0..dd91fb5ad2df 100644
--- a/frontend/src/scenes/web-analytics/common.test.ts
+++ b/frontend/src/scenes/web-analytics/common.test.ts
@@ -1,6 +1,7 @@
-import { PropertyFilterType, PropertyOperator } from '~/types'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { InsightLogicProps, PropertyFilterType, PropertyOperator } from '~/types'
-import { exactMatchOperatorFor } from './common'
+import { TileId, WebAnalyticsTile, exactMatchOperatorFor, withPresetTag } from './common'
describe('exactMatchOperatorFor', () => {
it.each([
@@ -14,3 +15,93 @@ describe('exactMatchOperatorFor', () => {
expect(exactMatchOperatorFor(key, type, doPathCleaning)).toBe(expected)
})
})
+
+describe('withPresetTag', () => {
+ const insightProps = {} as InsightLogicProps
+ const layout = {}
+
+ // A tagged node must already carry tags, mirroring how every web analytics tile is
+ // built with WEB_ANALYTICS_DEFAULT_QUERY_TAGS.
+ const sourceNode = (): any => ({
+ kind: NodeKind.WebOverviewQuery,
+ properties: [],
+ tags: { productKey: 'web_analytics' },
+ })
+
+ const tiles = (): WebAnalyticsTile[] => [
+ {
+ kind: 'query',
+ tileId: TileId.OVERVIEW,
+ layout,
+ insightProps,
+ query: { kind: NodeKind.InsightVizNode, source: sourceNode() } as any,
+ },
+ {
+ kind: 'tabs',
+ tileId: TileId.SOURCES,
+ layout,
+ activeTabId: 'a',
+ setTabId: () => {},
+ tabs: [
+ {
+ id: 'a',
+ title: 'a',
+ linkText: 'a',
+ insightProps,
+ query: { kind: NodeKind.DataTableNode, source: sourceNode() } as any,
+ },
+ ],
+ },
+ {
+ kind: 'section',
+ tileId: TileId.GRAPHS,
+ layout,
+ tiles: [
+ {
+ kind: 'query',
+ tileId: TileId.PATHS,
+ layout,
+ insightProps,
+ query: { kind: NodeKind.InsightVizNode, source: sourceNode() } as any,
+ },
+ ],
+ },
+ { kind: 'replay', tileId: TileId.REPLAY, layout },
+ ]
+
+ it('stamps the preset id on every query, tab, and nested tile', () => {
+ const [query, tabs, section, replay] = withPresetTag(tiles(), 'abc123')
+
+ expect((query as any).query.source.tags).toEqual({ productKey: 'web_analytics', presetId: 'abc123' })
+ expect((tabs as any).tabs[0].query.source.tags.presetId).toBe('abc123')
+ expect((section as any).tiles[0].query.source.tags.presetId).toBe('abc123')
+ expect(replay).toEqual({ kind: 'replay', tileId: TileId.REPLAY, layout })
+ })
+
+ it('returns the same array when no preset is applied, so nothing refetches', () => {
+ const input = tiles()
+ expect(withPresetTag(input, null)).toBe(input)
+ })
+
+ it('stamps a wrapper that carries its own tags above an untagged source', () => {
+ const input: WebAnalyticsTile[] = [
+ {
+ kind: 'query',
+ tileId: TileId.WEB_VITALS,
+ layout,
+ insightProps,
+ query: {
+ kind: NodeKind.WebVitalsQuery,
+ tags: { productKey: 'web_analytics' },
+ source: { kind: NodeKind.TrendsQuery, series: [] },
+ } as any,
+ },
+ ]
+
+ const [tile] = withPresetTag(input, 'abc123')
+
+ expect((tile as any).query.tags).toEqual({ productKey: 'web_analytics', presetId: 'abc123' })
+ // The untagged source stays untagged: only nodes already carrying tags are stamped.
+ expect((tile as any).query.source.tags).toBeUndefined()
+ })
+})
diff --git a/frontend/src/scenes/web-analytics/common.ts b/frontend/src/scenes/web-analytics/common.ts
index 45085900d47d..4316c6ef9d45 100644
--- a/frontend/src/scenes/web-analytics/common.ts
+++ b/frontend/src/scenes/web-analytics/common.ts
@@ -544,6 +544,46 @@ export const MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS: QueryLogTags = {
productKey: ProductKey.MARKETING_ANALYTICS,
}
+const tagQueryNode = <T extends QuerySchema>(node: T, presetId: string): T => {
+ // Only extend tags that are already there. Nodes without them were left untagged on purpose,
+ // and creating one would change what the query log attributes to web analytics. Tags can sit
+ // on the wrapper, the source, or both (WebVitalsQuery tags the wrapper), so the node's own
+ // tags are stamped before recursing rather than instead of it.
+ const tags = (node as { tags?: QueryLogTags }).tags
+ const tagged = tags ? { ...node, tags: { ...tags, presetId } } : node
+ const source = (tagged as { source?: QuerySchema }).source
+ if (source) {
+ return { ...tagged, source: tagQueryNode(source, presetId) }
+ }
+ return tagged
+}
+
+/**
+ * Stamp the applied filter preset's short id onto every tile query, so the warming job can find the
+ * shapes a preset actually produces. `tags` is stripped from both the query cache key and the
+ * warmer's shape key, so this never fragments either.
+ */
+export const withPresetTag = (tiles: WebAnalyticsTile[], presetId: string | null): WebAnalyticsTile[] => {
+ if (!presetId) {
+ return tiles
+ }
+ return tiles.map((tile): WebAnalyticsTile => {
+ switch (tile.kind) {
+ case 'query':
+ case 'error_tracking':
+ return { ...tile, query: tagQueryNode(tile.query, presetId) }
+ case 'tabs':
+ return { ...tile, tabs: tile.tabs.map((tab) => ({ ...tab, query: tagQueryNode(tab.query, presetId) })) }
+ case 'section':
+ return { ...tile, tiles: withPresetTag(tile.tiles, presetId) }
+ case 'replay':
+ return tile
+ default:
+ throw new UnexpectedNeverError(tile)
+ }
+ })
+}
+
export const checkCustomEventConversionGoalHasSessionIdsHelper = async (
conversionGoal: WebAnalyticsConversionGoal | null,
breakpoint: BreakPointFunction | undefined,
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsFilterLogic.ts b/frontend/src/scenes/web-analytics/webAnalyticsFilterLogic.ts
index d0b617b27c9a..cdae8712dfc1 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsFilterLogic.ts
+++ b/frontend/src/scenes/web-analytics/webAnalyticsFilterLogic.ts
@@ -67,6 +67,8 @@ export const isLiveStreamFilter = (filter: AnyPropertyFilter): filter is EventPr
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface webAnalyticsFilterLogicValues {
rawAuthorizedUrls: string[] // authorizedUrlListLogic
+ appliedPresetFilters: WebAnalyticsFiltersConfig | null
+ appliedPresetShortId: string | null
authorizedDomains: string[]
compareFilter: CompareFilter
countryFilter: string | null
@@ -90,6 +92,13 @@ export interface webAnalyticsFilterLogicActions {
loadPreset: (filters: WebAnalyticsFiltersConfig) => {
filters: WebAnalyticsFiltersConfig
}
+ setAppliedPreset: (
+ shortId: string | null,
+ filters: WebAnalyticsFiltersConfig | null
+ ) => {
+ filters: WebAnalyticsFiltersConfig | null
+ shortId: string | null
+ }
setCompareFilter: (compareFilter: CompareFilter) => {
compareFilter: CompareFilter
}
@@ -198,6 +207,13 @@ export const webAnalyticsFilterLogic: LogicWrapper<webAnalyticsFilterLogicType>
setReferrerFilter: (referrer: string | null) => ({ referrer }),
setCompareFilter: (compareFilter: CompareFilter) => ({ compareFilter }),
loadPreset: (filters: WebAnalyticsFiltersConfig) => ({ filters }),
+ // Mirrors webAnalyticsFilterPresetsLogic's own `appliedPreset`. It lives here too because
+ // webAnalyticsLogic needs it to tag queries, and it already connects to this logic while
+ // the presets logic connects to it — a reverse edge would be circular.
+ setAppliedPreset: (shortId: string | null, filters: WebAnalyticsFiltersConfig | null) => ({
+ shortId,
+ filters,
+ }),
clearFilters: true,
}),
reducers(({ props }) => ({
@@ -342,6 +358,24 @@ export const webAnalyticsFilterLogic: LogicWrapper<webAnalyticsFilterLogicType>
loadPreset: (_, { filters }) => (filters.compareFilter as CompareFilter) ?? { compare: true },
},
],
+ // Not persisted: the presets logic reloads and re-applies presets on mount, so a persisted
+ // copy here would outlive a preset that was deleted or renamed between sessions.
+ appliedPresetShortId: [
+ null as string | null,
+ {
+ setAppliedPreset: (_, { shortId }) => shortId,
+ loadPreset: () => null,
+ clearFilters: () => null,
+ },
+ ],
+ appliedPresetFilters: [
+ null as WebAnalyticsFiltersConfig | null,
+ {
+ setAppliedPreset: (_, { filters }) => filters,
+ loadPreset: () => null,
+ clearFilters: () => null,
+ },
+ ],
})),
selectors({
hasHostFilter: [
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsFilterPresetsLogic.ts b/frontend/src/scenes/web-analytics/webAnalyticsFilterPresetsLogic.ts
index ac78d45cb0f4..79b438c77a91 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsFilterPresetsLogic.ts
+++ b/frontend/src/scenes/web-analytics/webAnalyticsFilterPresetsLogic.ts
@@ -43,6 +43,13 @@ export interface webAnalyticsFilterPresetsLogicActions {
loadPreset: (filters: WebAnalyticsFiltersConfig) => {
filters: WebAnalyticsFiltersConfig
} // webAnalyticsFilterLogic
+ setAppliedPresetFilterState: (
+ shortId: string | null,
+ filters: WebAnalyticsFiltersConfig | null
+ ) => {
+ filters: WebAnalyticsFiltersConfig | null
+ shortId: string | null
+ } // webAnalyticsFilterLogic
clearDateFilters: () => {
value: true
} // webAnalyticsLogic
@@ -212,7 +219,7 @@ export const webAnalyticsFilterPresetsLogic = kea<webAnalyticsFilterPresetsLogic
values: [webAnalyticsLogic, ['currentFiltersConfig']],
actions: [
webAnalyticsFilterLogic,
- ['loadPreset', 'clearFilters as clearPropertyFilters'],
+ ['loadPreset', 'clearFilters as clearPropertyFilters', 'setAppliedPreset as setAppliedPresetFilterState'],
webAnalyticsLogic,
['clearFilters as clearDateFilters'],
],
@@ -322,6 +329,13 @@ export const webAnalyticsFilterPresetsLogic = kea<webAnalyticsFilterPresetsLogic
},
})),
listeners(({ actions, values }) => ({
+ // Keep webAnalyticsFilterLogic's copy in step so webAnalyticsLogic can tag queries with the
+ // preset. The other two transitions of the `appliedPreset` reducer (`loadPreset` and
+ // `clearFilters` via `clearPreset`) are webAnalyticsFilterLogic's own actions, so they
+ // already clear it there.
+ setAppliedPreset: ({ preset }) => {
+ actions.setAppliedPresetFilterState(preset?.short_id ?? null, preset?.filters ?? null)
+ },
applyPreset: ({ preset }) => {
if (values.appliedPreset?.short_id === preset.short_id) {
actions.clearPreset()
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
index ed07877c4792..016bd1cf59f7 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
@@ -21,6 +21,7 @@ import {
MarketingAnalyticsTab,
marketingAnalyticsLogic,
} from './tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+import { webAnalyticsFilterLogic } from './webAnalyticsFilterLogic'
import { webAnalyticsLogic } from './webAnalyticsLogic'
describe('webAnalyticsLogic focus mode', () => {
@@ -851,3 +852,46 @@ describe('webAnalyticsLogic URL restoration', () => {
expect(logic.values.rawWebAnalyticsFilters).toEqual([FILTER_A])
})
})
+
+describe('webAnalyticsLogic warmablePresetShortId', () => {
+ let logic: ReturnType<typeof webAnalyticsLogic.build>
+
+ beforeEach(() => {
+ localStorage.clear()
+ initKeaTests()
+ jest.spyOn(api.propertyDefinitions, 'list').mockResolvedValue({ results: [] } as any)
+ jest.spyOn(api.hogFunctions, 'list').mockResolvedValue({ results: [] } as any)
+ featureFlagLogic.mount()
+ logic = webAnalyticsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ const applyPreset = (): void => {
+ webAnalyticsFilterLogic.actions.loadPreset(logic.values.currentFiltersConfig)
+ webAnalyticsFilterLogic.actions.setAppliedPreset('abc123', logic.values.currentFiltersConfig)
+ }
+
+ it('tags queries while the applied preset still matches the filters', () => {
+ expect(logic.values.warmablePresetShortId).toBeNull()
+
+ applyPreset()
+
+ expect(logic.values.warmablePresetShortId).toBe('abc123')
+ })
+
+ it('stops tagging as soon as the user drifts off the preset', () => {
+ applyPreset()
+
+ // An applied preset stays applied while the filters move, so without the equality
+ // check the warmer would attribute unrelated shapes to this preset.
+ webAnalyticsFilterLogic.actions.togglePropertyFilter(PropertyFilterType.Event, '$browser', 'Chrome')
+
+ expect(logic.values.appliedPresetShortId).toBe('abc123')
+ expect(logic.values.warmablePresetShortId).toBeNull()
+ })
+})
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
index 8b9d3008a117..28ecf1055aa0 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
@@ -126,6 +126,7 @@ import {
loadPriorityMap,
personPropertiesToPathClean,
sessionPropertiesToPathClean,
+ withPresetTag,
} from './common'
import {
PROPERTY_HOST,
@@ -161,6 +162,8 @@ export interface webAnalyticsLogicValues {
currentTeam: TeamPublicType | TeamType | null // teamLogic
hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
user: UserType | null // userLogic
+ appliedPresetFilters: WebAnalyticsFiltersConfig | null // webAnalyticsFilterLogic
+ appliedPresetShortId: string | null // webAnalyticsFilterLogic
authorizedDomains: string[] // webAnalyticsFilterLogic
countryFilter: string | null // webAnalyticsFilterLogic
deviceTypeFilter: DeviceType | null // webAnalyticsFilterLogic
@@ -214,6 +217,7 @@ export interface webAnalyticsLogicValues {
graphsTab: string
hasCountryFilter: boolean
hasIncompatibleFilters: boolean
+ hasNonDefaultFilters: boolean
hasSavedFocusMode: boolean
hasSeenFocusModeOnboarding: boolean
hiddenTiles: TileId[]
@@ -252,6 +256,7 @@ export interface webAnalyticsLogicValues {
tileVisualizations: Record<TileId, TileVisualizationOption>
tiles: WebAnalyticsTile[]
useWebAnalyticsPrecompute: boolean | null
+ warmablePresetShortId: string | null
webAnalyticsFilters: WebAnalyticsPropertyFilters
webVitalsMetricQuery: InsightVizNode<TrendsQuery>
webVitalsPercentile: WebVitalsPercentile
@@ -561,6 +566,19 @@ export interface webAnalyticsLogicMeta {
isPathCleaningEnabled: boolean,
shouldFilterTestAccounts: boolean
) => WebAnalyticsFiltersConfig
+ warmablePresetShortId: (
+ appliedPresetShortId: string | null, // webAnalyticsFilterLogic
+ appliedPresetFilters: WebAnalyticsFiltersConfig | null, // webAnalyticsFilterLogic
+ currentFiltersConfig: WebAnalyticsFiltersConfig
+ ) => string | null
+ hasNonDefaultFilters: (
+ rawWebAnalyticsFilters: WebAnalyticsPropertyFilters, // webAnalyticsFilterLogic
+ domainFilter: string | null, // webAnalyticsFilterLogic
+ deviceTypeFilter: DeviceType | null, // webAnalyticsFilterLogic
+ countryFilter: string | null, // webAnalyticsFilterLogic
+ referrerFilter: string | null, // webAnalyticsFilterLogic
+ conversionGoal: WebAnalyticsConversionGoal | null
+ ) => boolean
webAnalyticsFilters: (
rawWebAnalyticsFilters: WebAnalyticsPropertyFilters,
isPathCleaningEnabled: boolean,
@@ -680,7 +698,8 @@ export interface webAnalyticsLogicMeta {
isGreaterThanMd: boolean,
tileVisualizations: Record<TileId, TileVisualizationOption>,
preAggregatedEnabled: boolean | undefined,
- hiddenTiles: TileId[]
+ hiddenTiles: TileId[],
+ warmablePresetShortId: string | null
) => WebAnalyticsTile[]
getNewInsightUrl: (
tiles: WebAnalyticsTile[]
@@ -728,6 +747,8 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
'validatedDomainFilter',
'selectedHost',
'authorizedDomains',
+ 'appliedPresetShortId',
+ 'appliedPresetFilters',
],
],
actions: [
@@ -1277,6 +1298,47 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
shouldFilterTestAccounts,
}),
],
+ // The preset id to tag queries with, or null. An applied preset stays applied while the
+ // user drifts the filters away from it, so tagging off `appliedPresetShortId` alone would
+ // attribute unrelated query shapes to the preset and blow past the warmer's per-preset cap.
+ warmablePresetShortId: [
+ (s) => [s.appliedPresetShortId, s.appliedPresetFilters, s.currentFiltersConfig],
+ (
+ appliedPresetShortId: string | null,
+ appliedPresetFilters: WebAnalyticsFiltersConfig | null,
+ currentFiltersConfig: WebAnalyticsFiltersConfig
+ ): string | null =>
+ appliedPresetShortId && appliedPresetFilters && objectsEqual(appliedPresetFilters, currentFiltersConfig)
+ ? appliedPresetShortId
+ : null,
+ ],
+ // Whether the user has filtered beyond the defaults, which is when saving a preset starts to
+ // pay off. Date range and the path-cleaning / test-account toggles are deliberately left out:
+ // almost everyone changes the date range, so counting it would nudge almost everyone.
+ hasNonDefaultFilters: [
+ (s) => [
+ s.rawWebAnalyticsFilters,
+ s.domainFilter,
+ s.deviceTypeFilter,
+ s.countryFilter,
+ s.referrerFilter,
+ s.conversionGoal,
+ ],
+ (
+ properties: WebAnalyticsPropertyFilters,
+ domainFilter: string | null,
+ deviceTypeFilter: DeviceType | null,
+ countryFilter: string | null,
+ referrerFilter: string | null,
+ conversionGoal: WebAnalyticsConversionGoal | null
+ ): boolean =>
+ properties.length > 0 ||
+ !!domainFilter ||
+ !!deviceTypeFilter ||
+ !!countryFilter ||
+ !!referrerFilter ||
+ !!conversionGoal,
+ ],
webAnalyticsFilters: [
(s) => [
s.rawWebAnalyticsFilters,
@@ -1633,6 +1695,7 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
s.tileVisualizations,
s.preAggregatedEnabled,
s.hiddenTiles,
+ s.warmablePresetShortId,
],
(
productTab: ProductTab,
@@ -1658,7 +1721,8 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
isGreaterThanMd: boolean,
tileVisualizations: Record<TileId, TileVisualizationOption>,
preAggregatedEnabled: boolean | undefined,
- hiddenTiles: TileId[]
+ hiddenTiles: TileId[],
+ warmablePresetShortId: string | null
): WebAnalyticsTile[] => {
const dateRange = { date_from: dateFrom, date_to: dateTo }
@@ -1900,74 +1964,83 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
math_property: `$web_vitals_${name}_value`,
})
- return [
- {
- kind: 'query',
- tileId: TileId.WEB_VITALS,
- layout: {
- colSpanClassName: 'md:col-span-full',
- orderWhenLargeClassName: '2xl:order-0',
+ // Tagged like the analytics tab below: web vitals shapes opened under a preset
+ // must reach the warmer too.
+ return withPresetTag(
+ [
+ {
+ kind: 'query',
+ tileId: TileId.WEB_VITALS,
+ layout: {
+ colSpanClassName: 'md:col-span-full',
+ orderWhenLargeClassName: '2xl:order-0',
+ },
+ query: {
+ kind: NodeKind.WebVitalsQuery,
+ properties: webAnalyticsFilters,
+ // Match the path-breakdown tile below so both tiles' precompute
+ // reads hash to the same bucket job and share warm buckets. The
+ // timeseries merges across all paths, so cleaning is result-neutral
+ // here, but the hash is not — a mismatch builds a second bucket set.
+ doPathCleaning: isPathCleaningEnabled,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ dateRange,
+ interval,
+ series: (['INP', 'LCP', 'CLS', 'FCP'] as WebVitalsMetric[]).map((metric) =>
+ createSeries(metric, webVitalsPercentile)
+ ),
+ trendsFilter: { display: ChartDisplayType.ActionsLineGraph },
+ filterTestAccounts,
+ properties: webAnalyticsFilters,
+ },
+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
+ },
+ insightProps: {
+ dashboardItemId: getDashboardItemId(
+ TileId.WEB_VITALS,
+ 'web-vitals-overview',
+ false
+ ),
+ loadPriority: loadPriorityMap[TileId.WEB_VITALS],
+ dataNodeCollectionId: WEB_ANALYTICS_DATA_COLLECTION_NODE_ID,
+ },
+ showIntervalSelect: true,
},
- query: {
- kind: NodeKind.WebVitalsQuery,
- properties: webAnalyticsFilters,
- // Match the path-breakdown tile below so both tiles' precompute
- // reads hash to the same bucket job and share warm buckets. The
- // timeseries merges across all paths, so cleaning is result-neutral
- // here, but the hash is not — a mismatch builds a second bucket set.
- doPathCleaning: isPathCleaningEnabled,
- source: {
- kind: NodeKind.TrendsQuery,
+ {
+ kind: 'query',
+ tileId: TileId.WEB_VITALS_PATH_BREAKDOWN,
+ layout: {
+ colSpanClassName: 'md:col-span-full',
+ orderWhenLargeClassName: '2xl:order-0',
+ },
+ query: {
+ kind: NodeKind.WebVitalsPathBreakdownQuery,
dateRange,
- interval,
- series: (['INP', 'LCP', 'CLS', 'FCP'] as WebVitalsMetric[]).map((metric) =>
- createSeries(metric, webVitalsPercentile)
- ),
- trendsFilter: { display: ChartDisplayType.ActionsLineGraph },
filterTestAccounts,
properties: webAnalyticsFilters,
+ percentile: webVitalsPercentile,
+ metric: webVitalsTab,
+ doPathCleaning: isPathCleaningEnabled,
+ thresholds: [
+ WEB_VITALS_THRESHOLDS[webVitalsTab].good,
+ WEB_VITALS_THRESHOLDS[webVitalsTab].poor,
+ ],
+ useWebAnalyticsPrecompute,
+ },
+ insightProps: {
+ dashboardItemId: getDashboardItemId(
+ TileId.WEB_VITALS_PATH_BREAKDOWN,
+ 'web-vitals-path-breakdown',
+ false
+ ),
+ loadPriority: loadPriorityMap[TileId.WEB_VITALS_PATH_BREAKDOWN],
+ dataNodeCollectionId: WEB_ANALYTICS_DATA_COLLECTION_NODE_ID,
},
- tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
- },
- insightProps: {
- dashboardItemId: getDashboardItemId(TileId.WEB_VITALS, 'web-vitals-overview', false),
- loadPriority: loadPriorityMap[TileId.WEB_VITALS],
- dataNodeCollectionId: WEB_ANALYTICS_DATA_COLLECTION_NODE_ID,
- },
- showIntervalSelect: true,
- },
- {
- kind: 'query',
- tileId: TileId.WEB_VITALS_PATH_BREAKDOWN,
- layout: {
- colSpanClassName: 'md:col-span-full',
- orderWhenLargeClassName: '2xl:order-0',
- },
- query: {
- kind: NodeKind.WebVitalsPathBreakdownQuery,
- dateRange,
- filterTestAccounts,
- properties: webAnalyticsFilters,
- percentile: webVitalsPercentile,
- metric: webVitalsTab,
- doPathCleaning: isPathCleaningEnabled,
- thresholds: [
- WEB_VITALS_THRESHOLDS[webVitalsTab].good,
- WEB_VITALS_THRESHOLDS[webVitalsTab].poor,
- ],
- useWebAnalyticsPrecompute,
- },
- insightProps: {
- dashboardItemId: getDashboardItemId(
- TileId.WEB_VITALS_PATH_BREAKDOWN,
- 'web-vitals-path-breakdown',
- false
- ),
- loadPriority: loadPriorityMap[TileId.WEB_VITALS_PATH_BREAKDOWN],
- dataNodeCollectionId: WEB_ANALYTICS_DATA_COLLECTION_NODE_ID,
},
- },
- ]
+ ],
+ warmablePresetShortId
+ )
}
const useTileHeaderV2 = featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_TILE_HEADER_V2] === 'test'
@@ -3076,12 +3149,15 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
return []
}
- return allTiles
- .filter(isNotNil)
- .filter((tile) =>
- preAggregatedEnabled ? TILES_ALLOWED_ON_PRE_AGGREGATED.includes(tile.tileId) : true
- )
- .filter((tile) => !hiddenTiles.includes(tile.tileId))
+ return withPresetTag(
+ allTiles
+ .filter(isNotNil)
+ .filter((tile) =>
+ preAggregatedEnabled ? TILES_ALLOWED_ON_PRE_AGGREGATED.includes(tile.tileId) : true
+ )
+ .filter((tile) => !hiddenTiles.includes(tile.tileId)),
+ warmablePresetShortId
+ )
},
],
getNewInsightUrl: [(s) => [s.tiles], (tiles: WebAnalyticsTile[]) => getNewInsightUrlFactory(tiles)],
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index bfb7dc48abde..40ac7813e5dc 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -435,6 +435,10 @@ class QueryTags(BaseModel):
# frontend UI context (from QueryLogTags)
scene: Optional[str] = None
+ # Saved Web analytics filter preset the query was run under. Client-supplied and
+ # truncated at the boundary; the warming DAG validates it against Postgres before
+ # acting on it, so an invented id buys nothing.
+ preset_id: Optional[str] = None
alert_config_id: Optional[uuid.UUID] = None
# Cadence and query shape of the alert that triggered this run, tagged at evaluation
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index e351034af164..81e5f2e5dd88 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -286,6 +286,10 @@ _REFRESH_TO_EXECUTION_MODE: dict[str | bool, ExecutionMode] = { # ty: ignore[in
UNKNOWN_QUERY_METRIC_LABEL = "unknown"
SURVEYS_PRODUCT_KEY = "surveys"
+# Matches WebAnalyticsFilterPreset.short_id's max_length. The value is client-supplied,
+# so it is truncated rather than trusted before it reaches the query log.
+PRESET_ID_MAX_LENGTH = 12
+
def get_survey_query_metric_labels(query: Any) -> dict[str, str] | None:
tags = getattr(query, "tags", None)
@@ -2220,6 +2224,11 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
if tags.scene:
posthoganalytics.tag("scene", tags.scene)
tag_queries(scene=tags.scene)
+ # Dropped, not truncated: truncating an overlong client value could alias it
+ # onto a real preset's short id and attribute shapes to someone else's preset.
+ if tags.presetId and len(tags.presetId) <= PRESET_ID_MAX_LENGTH:
+ posthoganalytics.tag("preset_id", tags.presetId)
+ tag_queries(preset_id=tags.presetId)
tag_queries(execution_mode=execution_mode.value)
tag_queries(cache_key=cache_key)
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index f786d10ccfb2..7495ae35deae 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -699,6 +699,20 @@ class TestQueryRunner(BaseTest):
cache_key = runner.get_cache_key()
assert cache_key == "cache_42_13361de10d0c3c79451b288eb57ca1147331e86a8b8e63a0a815adf5a2d7bcbb"
+ def test_cache_key_ignores_query_log_tags(self):
+ # Query log tags are metadata, so they must never partition the cache. Web
+ # analytics warming leans on this: it stamps the applied filter preset's id into
+ # tags so it can find the shapes a preset produces, and a tagged query has to keep
+ # reading the same cache entry as the untagged one, or every preset user would
+ # miss the cache on every load and the warm set would double.
+ TestQueryRunner = self.setup_test_query_runner_class()
+ team = Team.objects.create(pk=42, organization=self.organization)
+
+ untagged = TestQueryRunner(query={"some_attr": "bla"}, team=team)
+ tagged = TestQueryRunner(query={"some_attr": "bla", "tags": {"presetId": "abc123"}}, team=team)
+
+ assert tagged.get_cache_key() == untagged.get_cache_key()
+
@override_settings(PERSON_ON_EVENTS_OVERRIDE=False, PERSON_ON_EVENTS_V2_OVERRIDE=False)
def test_cache_key_runner_subclass(self):
TestQueryRunner = self.setup_test_query_runner_class()
diff --git a/posthog/schema.py b/posthog/schema.py
index 2944f34ca1b6..25f710bc4729 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -2624,6 +2624,10 @@ class QueryLogTags(BaseModel):
default=None,
description=("Name of the query, preferably unique. For example web_analytics_vitals"),
)
+ presetId: str | None = Field(
+ default=None,
+ description=("Short id of the saved Web analytics filter preset this query was run under, if any."),
+ )
productKey: str | None = Field(
default=None,
description=(
diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.py
index 561823875d5d..af801e10d39d 100644
--- a/posthog/settings/dynamic_settings.py
+++ b/posthog/settings/dynamic_settings.py
@@ -384,6 +384,14 @@ CONSTANCE_CONFIG = {
"CPU to match (dagster-k8s/config on the job). Clamped to 1-16; applies at the next run.",
int,
),
+ "WEB_ANALYTICS_WARMING_PRESET_LANE_ENABLED": (
+ get_from_env("WEB_ANALYTICS_WARMING_PRESET_LANE_ENABLED", default=False, type_cast=str_to_bool),
+ "Whether web analytics warming also selects the query shapes teams ran under a saved filter "
+ "preset, below the usual demand floor. Bounded per team by the preset lane's own caps. The "
+ "flag is part of the selection cache key, so turning it off drops preset shapes on the next "
+ "run rather than at the end of the cache TTL.",
+ bool,
+ ),
}
SETTINGS_ALLOWING_API_OVERRIDE = (
@@ -449,6 +457,7 @@ SETTINGS_ALLOWING_API_OVERRIDE = (
"WEB_ANALYTICS_WARMING_MAX_SHAPES",
"WEB_ANALYTICS_WARMING_SHARD_THREADS",
"WEB_ANALYTICS_WARMING_SHARDS",
+ "WEB_ANALYTICS_WARMING_PRESET_LANE_ENABLED",
)
# SECRET_SETTINGS can only be updated but will never be exposed through the API (we do store them plain text in the DB)
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 3ede9b98a6c9..d522116e958f 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -1830,6 +1830,8 @@ export interface AccountsTableSortApi {
export interface QueryLogTagsApi {
/** Name of the query, preferably unique. For example web_analytics_vitals */
name?: string | null
+ /** Short id of the saved Web analytics filter preset this query was run under, if any. */
+ presetId?: string | null
/** Product responsible for this query. Use string, there's no need to churn the Schema when we add a new product * */
productKey?: string | null
/** Scene where this query is shown in the UI. Use string, there's no need to churn the Schema when we add a new Scene * */
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index efba6469719b..1e7b495931f8 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -2779,6 +2779,8 @@ export interface GroupNodeApi {
export interface QueryLogTagsApi {
/** Name of the query, preferably unique. For example web_analytics_vitals */
name?: string | null
+ /** Short id of the saved Web analytics filter preset this query was run under, if any. */
+ presetId?: string | null
/** Product responsible for this query. Use string, there's no need to churn the Schema when we add a new product * */
productKey?: string | null
/** Scene where this query is shown in the UI. Use string, there's no need to churn the Schema when we add a new Scene * */
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 95051a7c0c36..d1b2d7495934 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -1739,6 +1739,8 @@ export interface GroupNodeApi {
export interface QueryLogTagsApi {
/** Name of the query, preferably unique. For example web_analytics_vitals */
name?: string | null
+ /** Short id of the saved Web analytics filter preset this query was run under, if any. */
+ presetId?: string | null
/** Product responsible for this query. Use string, there's no need to churn the Schema when we add a new product * */
productKey?: string | null
/** Scene where this query is shown in the UI. Use string, there's no need to churn the Schema when we add a new Scene * */
diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.py
index 06cb6a870281..422c3ac387a4 100644
--- a/products/web_analytics/dags/cache_warming.py
+++ b/products/web_analytics/dags/cache_warming.py
@@ -74,12 +74,21 @@ WARMING_SHAPES_SELECTED_GAUGE = Gauge(
"posthog_web_analytics_warming_shapes_selected",
"Number of hot query shapes selected for web analytics warming in the last run",
)
+WARMING_PRESET_SHAPES_SELECTED_GAUGE = Gauge(
+ "posthog_web_analytics_warming_preset_shapes_selected",
+ "Number of selected shapes attributed to a saved filter preset in the last run",
+)
+WARMING_PRESETS_SELECTED_GAUGE = Gauge(
+ "posthog_web_analytics_warming_presets_selected",
+ "Number of distinct saved filter presets the last selection kept shapes for",
+)
WARMING_QUERIES_COUNTER = Counter(
"posthog_web_analytics_warming_queries_total",
"Web analytics warming outcomes per query shape",
- # warmed | skipped_fresh | skipped_duplicate | skipped_raw_low_demand |
+ # outcome: warmed | skipped_fresh | skipped_duplicate | skipped_raw_low_demand |
# skipped_cold | skipped_already_warmed | failed | unsupported
- ["outcome"],
+ # lane: demand (selected by query volume) | preset (selected by a saved filter preset)
+ ["outcome", "lane"],
)
logger = structlog.get_logger(__name__)
@@ -102,6 +111,24 @@ LAZY_PRECOMPUTE_QUERY_KINDS = frozenset(
# (the queries replay outside the tenant's own request throttles).
MAX_SHAPES_PER_TEAM = 100
+# The preset lane: shapes a team ran while a saved filter preset was applied. Exploration
+# rarely clears the demand floor, so without this a preset stays permanently cold — which
+# is the whole reason someone saved it. The lane is bounded on three axes instead, all
+# enforced in Python against Postgres after the scan (ClickHouse can't see which presets
+# exist), so a client that invents preset ids in its query tags buys nothing.
+PRESET_LANE_MAX_PRESETS_PER_TEAM = 15
+# One dashboard render is ~15-20 distinct shapes; the headroom covers tab clicks and
+# breakdown re-sorts made with the preset still applied.
+PRESET_LANE_MAX_SHAPES_PER_PRESET = 25
+# Backstop for the union across a team's presets — they overlap heavily in practice, so
+# this bites well before 15 x 25 would.
+PRESET_LANE_MAX_SHAPES_PER_TEAM = 250
+# Bound on the preset ids collected per shape in ClickHouse, and on their length, so a
+# hostile client can't balloon the aggregate state before Postgres ever sees the ids.
+# The length matches WebAnalyticsFilterPreset.short_id's max_length.
+PRESET_LANE_MAX_IDS_PER_SHAPE = 10
+PRESET_ID_MAX_LENGTH = 12
+
# Demand is selected by API query kind, not by query_type tag: the tag
# vocabulary is a growing zoo of strategy variants (no_join, session_id_set,
# lazy reads, per-breakdown inserts, …) and enumerating it would silently drop
@@ -379,8 +406,139 @@ def build_replay_runner(
return runner, eligible_json, True
+# Teams per Postgres round trip when validating preset ids. Keeps the IN lists to a
+# size Postgres plans well while still being a handful of queries, not thousands.
+_PRESET_VALIDATION_TEAM_CHUNK = 500
+
+
+def _valid_preset_ids(ids_by_team: dict[int, set[str]]) -> set[tuple[int, str]]:
+ """The (team_id, short_id) pairs that are real, live presets.
+
+ ClickHouse only knows what clients claimed in their query tags, and that tag is
+ client-supplied, so nothing downstream may act on an id until Postgres has confirmed
+ it belongs to this team and is not deleted.
+ """
+ # WebAnalyticsFilterPreset is not on a fail-closed manager yet. If it ever is, this
+ # call site is genuinely cross-team and becomes `.all_teams` — not `for_team`, which
+ # is per-team and would turn one query into thousands.
+ from products.web_analytics.backend.models.web_analytics_filter_preset import ( # noqa: PLC0415 — keeps the Django model off the Dagster code-location import path
+ WebAnalyticsFilterPreset,
+ )
+
+ team_ids = sorted(ids_by_team)
+ valid: set[tuple[int, str]] = set()
+ for start in range(0, len(team_ids), _PRESET_VALIDATION_TEAM_CHUNK):
+ chunk = team_ids[start : start + _PRESET_VALIDATION_TEAM_CHUNK]
+ short_ids: set[str] = set()
+ for team_id in chunk:
+ short_ids |= ids_by_team[team_id]
+ valid.update(
+ WebAnalyticsFilterPreset.objects.filter(
+ team_id__in=chunk, deleted=False, short_id__in=sorted(short_ids)
+ ).values_list("team_id", "short_id")
+ )
+ return valid
+
+
+def _apply_preset_lane(context: dagster.OpExecutionContext, rows: list[dict], minimum_query_count: int) -> list[dict]:
+ """Validate the preset ids ClickHouse reported and hold the lane to its caps.
+
+ Every row keeps only the preset ids Postgres vouches for. A row left with none is no
+ longer a preset shape and falls back to the demand rules it was exempted from, which
+ is what makes an invented id worthless. Surviving rows are then bounded per preset
+ and per team, so no tenant can turn saved presets into unbounded background compute.
+ """
+ ids_by_team: dict[int, set[str]] = {}
+ for row in rows:
+ if row.get("preset_ids"):
+ ids_by_team.setdefault(row["team_id"], set()).update(row["preset_ids"])
+ claimed = sum(len(ids) for ids in ids_by_team.values())
+ valid = _valid_preset_ids(ids_by_team) if ids_by_team else set()
+
+ # Demand rank per (team, preset), used both to pick a team's 15 and to order shapes.
+ # Epoch seconds rather than datetimes: ClickHouse hands back naive values here, but a
+ # tz-aware one would make the comparison raise mid-selection.
+ last_seen_by_preset: dict[tuple[int, str], float] = {}
+ demand_by_preset: dict[tuple[int, str], int] = {}
+ for row in rows:
+ kept = [pid for pid in row.get("preset_ids") or [] if (row["team_id"], pid) in valid]
+ row["preset_ids"] = kept
+ # Popped, not kept: the selection is cached as JSON and a datetime would not
+ # serialize. Its only use is the ranking below.
+ last_seen = row.pop("preset_last_seen_at", None)
+ last_seen_at = last_seen.timestamp() if isinstance(last_seen, datetime) else 0.0
+ for pid in kept:
+ key = (row["team_id"], pid)
+ demand_by_preset[key] = demand_by_preset.get(key, 0) + row["query_count"]
+ last_seen_by_preset[key] = max(last_seen_by_preset.get(key, 0.0), last_seen_at)
+
+ # Which presets a team gets: most recently used first, demand breaking ties. Recency
+ # comes from the scan rather than the model's last_modified_at, which is a
+ # modification time — renaming a preset nobody opens must not outrank a daily one.
+ kept_presets: set[tuple[int, str]] = set()
+ presets_by_team: dict[int, list[str]] = {}
+ for team_id, preset_id in demand_by_preset:
+ presets_by_team.setdefault(team_id, []).append(preset_id)
+ for team_id, preset_ids in presets_by_team.items():
+ preset_ids.sort(
+ key=lambda pid: (last_seen_by_preset[(team_id, pid)], demand_by_preset[(team_id, pid)]), reverse=True
+ )
+ kept_presets.update((team_id, pid) for pid in preset_ids[:PRESET_LANE_MAX_PRESETS_PER_TEAM])
+ presets_dropped_over_cap = len(demand_by_preset) - len(kept_presets)
+
+ # Hottest shapes first, so every cap below truncates the tail rather than an
+ # arbitrary slice.
+ ordered = sorted(rows, key=lambda row: row["query_count"], reverse=True)
+
+ shapes_per_preset: dict[tuple[int, str], int] = {}
+ shapes_per_team: dict[int, int] = {}
+ demand_shapes_per_team: dict[int, int] = {}
+ selected: list[dict] = []
+ for row in ordered:
+ team_id = row["team_id"]
+ attributed = [pid for pid in row["preset_ids"] if (team_id, pid) in kept_presets]
+ attributed = [
+ pid for pid in attributed if shapes_per_preset.get((team_id, pid), 0) < PRESET_LANE_MAX_SHAPES_PER_PRESET
+ ]
+ if attributed and shapes_per_team.get(team_id, 0) < PRESET_LANE_MAX_SHAPES_PER_TEAM:
+ # One row can serve several presets but is warmed once, so it counts against
+ # each preset's budget and once against the team's.
+ for pid in attributed:
+ shapes_per_preset[(team_id, pid)] = shapes_per_preset.get((team_id, pid), 0) + 1
+ shapes_per_team[team_id] = shapes_per_team.get(team_id, 0) + 1
+ row["preset_ids"] = attributed
+ selected.append(row)
+ continue
+ # Not (or no longer) a preset shape: it has to earn its place on demand alone,
+ # against the same floor and per-team cap as everything else.
+ row["preset_ids"] = []
+ if row["query_count"] < minimum_query_count or demand_shapes_per_team.get(team_id, 0) >= MAX_SHAPES_PER_TEAM:
+ continue
+ demand_shapes_per_team[team_id] = demand_shapes_per_team.get(team_id, 0) + 1
+ selected.append(row)
+
+ context.log.info(
+ f"Preset lane: {len(kept_presets)} presets across {len(shapes_per_team)} teams, "
+ f"{sum(shapes_per_team.values())} shapes "
+ f"({claimed - len(valid)} claimed ids invalid, {presets_dropped_over_cap} presets over the per-team cap)"
+ )
+ logger.info(
+ "web_analytics_warming_preset_lane",
+ presets_selected=len(kept_presets),
+ preset_teams=len(shapes_per_team),
+ preset_shapes=sum(shapes_per_team.values()),
+ presets_invalid=claimed - len(valid),
+ presets_dropped_over_cap=presets_dropped_over_cap,
+ )
+ return selected
+
+
def queries_to_keep_fresh(
- context: dagster.OpExecutionContext, days: int = 2, minimum_query_count: int = 2, max_shapes: int = 40000
+ context: dagster.OpExecutionContext,
+ days: int = 2,
+ minimum_query_count: int = 2,
+ max_shapes: int = 40000,
+ preset_lane: bool = False,
) -> list[dict]:
"""Fleet-wide demand selection: every (team, query shape) with at least
`minimum_query_count` runs in the window, hottest first, capped at
@@ -389,10 +547,15 @@ def queries_to_keep_fresh(
The audience is implicit — any team with a hot shape is active on web
analytics and benefits from warming. One batched query replaces the previous
per-team loop, which could not scale past a handful of teams.
+
+ With `preset_lane`, shapes run under a saved filter preset are also selected,
+ below the demand floor and in their own per-team budget — see
+ `_apply_preset_lane`, which enforces the lane's caps once Postgres has said
+ which of the tagged preset ids are real.
"""
context.log.info(
f"Selecting fleet-wide web analytics queries with >= {minimum_query_count} runs "
- f"in the last {days} days (cap {max_shapes} shapes)."
+ f"in the last {days} days (cap {max_shapes} shapes, preset lane {'on' if preset_lane else 'off'})."
)
# Selection reads system.query_log across the whole cluster: Dagster connects
@@ -428,6 +591,51 @@ def queries_to_keep_fresh(
# background warmer — out of the demand counts, otherwise a once-warmed shape
# would keep itself hot forever. LIKE literals are %%-escaped because
# clickhouse_driver %-formats the query when params are passed.
+ # The preset lane's SQL is spliced in rather than always present, so with the lane off
+ # the scan does no extra JSON extraction, carries no extra aggregate state, and keeps
+ # the original HAVING — the kill switch costs the fleet nothing. Every fragment is
+ # built from module-level constants, so the nosemgrep rationale below still holds.
+ if preset_lane:
+ preset_row_columns = ", JSONExtractString(log_comment, 'preset_id') AS preset_id, event_time"
+ preset_variant_columns = (
+ f", groupUniqArrayIf({PRESET_LANE_MAX_IDS_PER_SHAPE})"
+ f"(preset_id, preset_id != '' AND length(preset_id) <= {PRESET_ID_MAX_LENGTH}) AS variant_preset_ids"
+ ", maxIf(event_time, preset_id != '') AS variant_preset_last_seen"
+ )
+ preset_outer_columns = (
+ # Bounded aggregate, not arrayDistinct(arrayFlatten(groupArray(...))): ignored-field
+ # variants each carry up to the per-variant cap of ids, so an unbounded outer merge
+ # would let one shape accumulate an attacker-sized id array (aggregate state included)
+ # before Postgres validation ever sees it.
+ f", groupUniqArrayArray({PRESET_LANE_MAX_IDS_PER_SHAPE})(variant_preset_ids) AS preset_ids"
+ ", max(variant_preset_last_seen) AS preset_last_seen_at"
+ # Whether the representative variant itself ran under a preset. The raw replay
+ # floor keys on this, not on shape-level tagging: raw replays aren't shared
+ # across variants, so a tagged sibling must not lower the bar for an untagged
+ # representative.
+ ", argMax(notEmpty(variant_preset_ids), variant_count) AS representative_preset_tagged"
+ # Priority is capped at the lane's own per-team budget so tagged rows beyond it
+ # (or with invented ids Postgres will reject later) compete on demand terms
+ # instead of evicting a team's real hot shapes before validation can run.
+ ", notEmpty(preset_ids)"
+ " AND row_number() OVER (PARTITION BY team_id, notEmpty(preset_ids) ORDER BY query_count DESC)"
+ f" <= {PRESET_LANE_MAX_SHAPES_PER_TEAM} AS preset_priority"
+ )
+ # A preset shape is kept whatever its demand — that is the point of the lane —
+ # and, up to the lane's per-team budget, sorted ahead of the demand lane so
+ # neither LIMIT can crowd it out. The per-team LIMIT is widened by the lane's
+ # own budget so the demand lane keeps its full MAX_SHAPES_PER_TEAM slots.
+ preset_having = "query_count >= %(minimum_query_count)s OR notEmpty(preset_ids)"
+ preset_order_by = "preset_priority DESC, "
+ max_shapes_per_team = MAX_SHAPES_PER_TEAM + PRESET_LANE_MAX_SHAPES_PER_TEAM
+ else:
+ preset_row_columns = ""
+ preset_variant_columns = ""
+ preset_outer_columns = ""
+ preset_having = "query_count >= %(minimum_query_count)s"
+ preset_order_by = ""
+ max_shapes_per_team = MAX_SHAPES_PER_TEAM
+
# nosemgrep: clickhouse-fstring-param-audit (interpolations are module-level constants from hardcoded tuples, not user input; everything dynamic is parameterized)
results = sync_execute(
f"""
@@ -452,12 +660,14 @@ def queries_to_keep_fresh(
-- normalization, so the warmer deepens it to the widest of these
-- (see deepen_to_widest_warmable_range).
groupUniqArray(JSONExtractString(query_json_raw, 'dateRange', 'date_from')) AS observed_date_froms
+ {preset_outer_columns}
FROM (
SELECT
team_id,
normalized_shape,
query_json_raw,
uniqExact(query_id) AS variant_count
+ {preset_variant_columns}
FROM (
SELECT
JSONExtractInt(log_comment, 'team_id') AS team_id,
@@ -488,6 +698,7 @@ def queries_to_keep_fresh(
JSONExtractString(log_comment, 'kind') AS request_kind,
JSONExtractRaw(log_comment, 'query') AS query_json_raw,
query_id
+ {preset_row_columns}
FROM clusterAllReplicas(%(cluster)s, system.query_log)
-- Filter the cheap native columns first so the big log_comment String
-- is read only for surviving rows. is_initial_query alone drops roughly
@@ -527,9 +738,9 @@ def queries_to_keep_fresh(
GROUP BY
team_id,
normalized_shape
- HAVING query_count >= %(minimum_query_count)s
+ HAVING {preset_having}
ORDER BY
- query_count DESC
+ {preset_order_by}query_count DESC
LIMIT %(max_shapes_per_team)s BY team_id
LIMIT %(max_shapes)s
""",
@@ -538,7 +749,7 @@ def queries_to_keep_fresh(
"days": days,
"minimum_query_count": minimum_query_count,
"max_shapes": max_shapes,
- "max_shapes_per_team": MAX_SHAPES_PER_TEAM,
+ "max_shapes_per_team": max_shapes_per_team,
"shape_ignored_fields": sorted(SHAPE_CAP_KEY_IGNORED_QUERY_FIELDS),
"kind_prefix": WARMABLE_QUERY_KIND_PREFIX,
"unwarmable_kinds": UNWARMABLE_QUERY_KINDS,
@@ -549,7 +760,7 @@ def queries_to_keep_fresh(
settings={"max_bytes_to_read": _SELECTION_MAX_BYTES_TO_READ, "max_execution_time": 600},
)
- return [
+ rows = [
{
"team_id": result[0],
# Faithful representative range — deepening happens in
@@ -559,9 +770,23 @@ def queries_to_keep_fresh(
"representative_query_count": result[3],
"normalized_query_hash": result[4],
"observed_date_froms": result[5],
+ # Preset ids ClickHouse saw on this shape, still unvalidated. Absent
+ # entirely when the lane is off, so downstream code can key on the field.
+ **(
+ {
+ "preset_ids": list(result[6]),
+ "preset_last_seen_at": result[7],
+ "representative_preset_tagged": bool(result[8]),
+ }
+ if preset_lane
+ else {}
+ ),
}
for result in results
]
+ if preset_lane:
+ rows = _apply_preset_lane(context, rows, minimum_query_count)
+ return rows
# The demand selection scans terabytes of query_log fleet-wide, so its result is
@@ -578,15 +803,15 @@ def queries_to_keep_fresh(
# miss — object storage has no per-key expiry of its own.
#
# The vN suffix versions the selection *logic*: the cache only validates the
-# settings params (days/min/max), not the query itself, so a change to the
-# selection query (new filter, different grouping) would otherwise keep replaying
+# settings params (days/min/max/preset lane), not the query itself, so a change to
+# the selection query (new filter, different grouping) would otherwise keep replaying
# a stale blob written by the old logic until its TTL expired. Bump the version
# whenever the selection query changes so the new logic takes effect on deploy.
-_WARMABLE_QUERIES_STORAGE_KEY = "web_analytics/warmable_queries/v5.json.gz"
+_WARMABLE_QUERIES_STORAGE_KEY = "web_analytics/warmable_queries/v6.json.gz"
def _read_cached_warmable_queries(
- days: int, minimum_query_count: int, max_shapes: int, ttl_seconds: int
+ days: int, minimum_query_count: int, max_shapes: int, preset_lane: bool, ttl_seconds: int
) -> Optional[list[dict]]:
# Fail open: any storage, decode, or unexpected-payload problem is treated as
# a miss so warming falls back to a fresh scan rather than erroring. The field
@@ -597,11 +822,15 @@ def _read_cached_warmable_queries(
if raw is None:
return None
payload = json.loads(gzip.decompress(raw))
- params_match = (payload["days"], payload["minimum_query_count"], payload["max_shapes"]) == (
- days,
- minimum_query_count,
- max_shapes,
- )
+ params_match = (
+ payload["days"],
+ payload["minimum_query_count"],
+ payload["max_shapes"],
+ # Part of the key so flipping the preset lane off drops preset shapes on the
+ # next run rather than at the end of the TTL — otherwise the kill switch is
+ # cosmetic for up to six hours.
+ payload["preset_lane"],
+ ) == (days, minimum_query_count, max_shapes, preset_lane)
is_fresh = time.time() - payload["generated_at"] < ttl_seconds
if not params_match or not is_fresh:
return None
@@ -611,11 +840,14 @@ def _read_cached_warmable_queries(
return None
-def _write_cached_warmable_queries(days: int, minimum_query_count: int, max_shapes: int, queries: list[dict]) -> None:
+def _write_cached_warmable_queries(
+ days: int, minimum_query_count: int, max_shapes: int, preset_lane: bool, queries: list[dict]
+) -> None:
payload = {
"days": days,
"minimum_query_count": minimum_query_count,
"max_shapes": max_shapes,
+ "preset_lane": preset_lane,
"generated_at": time.time(),
"queries": queries,
}
@@ -625,6 +857,18 @@ def _write_cached_warmable_queries(days: int, minimum_query_count: int, max_shap
logger.warning("web_analytics_warming_cache_write_failed", exc_info=True)
+def _summarize_preset_lane(queries: list[dict]) -> dict[str, int]:
+ """Shape counts for the preset lane, recomputed from the selection so the numbers
+ are the same whether it was scanned this run or read back from the cache."""
+ preset_shapes = [q for q in queries if q.get("preset_ids")]
+ presets = {(q["team_id"], pid) for q in preset_shapes for pid in q["preset_ids"]}
+ return {
+ "preset_shape_count": len(preset_shapes),
+ "preset_team_count": len({q["team_id"] for q in preset_shapes}),
+ "presets_selected": len(presets),
+ }
+
+
@dagster.op
def publish_volume_floor_op(context: dagster.OpExecutionContext) -> bool:
"""Refresh the above-floor team set the shared eligibility gate reads.
@@ -683,14 +927,19 @@ def get_warmable_queries_op(context: dagster.OpExecutionContext, floor_published
minimum_query_count = get_instance_setting("WEB_ANALYTICS_WARMING_MIN_QUERY_COUNT")
max_shapes = get_instance_setting("WEB_ANALYTICS_WARMING_MAX_SHAPES")
ttl_seconds = get_instance_setting("WEB_ANALYTICS_WARMING_SELECTION_TTL_SECONDS")
+ preset_lane = bool(get_instance_setting("WEB_ANALYTICS_WARMING_PRESET_LANE_ENABLED"))
- queries = _read_cached_warmable_queries(days, minimum_query_count, max_shapes, ttl_seconds)
+ queries = _read_cached_warmable_queries(days, minimum_query_count, max_shapes, preset_lane, ttl_seconds)
from_cache = queries is not None
if queries is None:
queries = queries_to_keep_fresh(
- context, days=days, minimum_query_count=minimum_query_count, max_shapes=max_shapes
+ context,
+ days=days,
+ minimum_query_count=minimum_query_count,
+ max_shapes=max_shapes,
+ preset_lane=preset_lane,
)
- _write_cached_warmable_queries(days, minimum_query_count, max_shapes, queries)
+ _write_cached_warmable_queries(days, minimum_query_count, max_shapes, preset_lane, queries)
# `selection_cap_reached` reflects the selection query alone: sticky entries
# are appended below and floor-dropped shapes still consumed cap slots, so
@@ -746,12 +995,17 @@ def get_warmable_queries_op(context: dagster.OpExecutionContext, floor_published
pre_floor_count = len(queries)
queries = [q for q in queries if is_team_above_volume_floor(int(q["team_id"]))]
floor_dropped = pre_floor_count - len(queries)
+ # Preset stats reflect the shapes actually warmed, so count them after the floor.
+ preset_stats = _summarize_preset_lane(queries)
team_count = len({q["team_id"] for q in queries})
WARMING_SHAPES_SELECTED_GAUGE.set(len(queries))
+ WARMING_PRESET_SHAPES_SELECTED_GAUGE.set(preset_stats["preset_shape_count"])
+ WARMING_PRESETS_SELECTED_GAUGE.set(preset_stats["presets_selected"])
source = "cached" if from_cache else "freshly selected"
context.log.info(
- f"Warming {len(queries)} {source} hot query shapes across {team_count} teams"
+ f"Warming {len(queries)} {source} hot query shapes across {team_count} teams "
+ f"({preset_stats['preset_shape_count']} from saved presets)"
+ (
f" (volume floor dropped {floor_dropped} shapes under "
f"{settings.WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS} events/7d)"
@@ -768,6 +1022,8 @@ def get_warmable_queries_op(context: dagster.OpExecutionContext, floor_published
"floor_dropped": floor_dropped,
"cap_reached": selection_cap_reached,
"from_cache": from_cache,
+ "preset_lane_enabled": preset_lane,
+ **preset_stats,
}
)
return queries
@@ -778,6 +1034,21 @@ def get_warmable_queries_op(context: dagster.OpExecutionContext, floor_published
# replays amplify a tenant's two runs into hourly background scans.
RAW_REPLAY_MIN_QUERY_COUNT = 10
+# The same bar for preset shapes. Not a bypass: a raw replay is a full live query every
+# stale hour, so exempting it entirely is exactly where the lane's cost would blow up.
+# But at 10 a preset with a conversion goal (raw-only) would never warm, which is the
+# promise the lane exists to keep — so a preset earns its replay at two loads in the
+# window instead. The lower floor applies only when the representative variant itself
+# ran under the preset, and raw preset replays are further capped per team below.
+PRESET_RAW_REPLAY_MIN_QUERY_COUNT = 2
+
+# Raw preset replays a team can warm per pass. Validated preset ids prove membership,
+# not that the query matches the preset, so without this cap a team member could tag
+# arbitrary expensive raw-only shapes and have the warmer rerun them hourly. One
+# preset's worth of shapes keeps the conversion-goal promise while bounding the
+# amplification to a fraction of the lane's overall budget.
+PRESET_LANE_MAX_RAW_SHAPES_PER_TEAM = PRESET_LANE_MAX_SHAPES_PER_PRESET
+
# Worker threads for the warm pass. The pass is IO-bound (cache checks, CH
# reads/inserts), so a pool cuts wall time at the widened selection size. A cold
# first run is dominated by per-day bucket builds — hundreds of thousands of them
@@ -957,6 +1228,8 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
# Selection groups by raw JSON text, so differently-encoded rows can
# normalize to one cache key; first worker to claim it warms, the rest skip.
seen_cache_keys: set[tuple[int, str]] = set()
+ # Raw (non-lazy) preset replays warmed this pass, per team — see the budget gate below.
+ raw_preset_replays_by_team: dict[int, int] = {}
seen_lock = threading.Lock()
def _warm_one(query_info: dict) -> str:
@@ -983,6 +1256,8 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
was_cold=query_info.get("_was_cold"),
capacity_retries=query_info.get("_capacity_retries"),
normalized_query_hash=query_info.get("normalized_query_hash"),
+ lane="preset" if query_info.get("preset_ids") else "demand",
+ preset_ids=query_info.get("preset_ids") or None,
)
except Exception:
# Observability must never abort the pass: a malformed shape already
@@ -991,6 +1266,9 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
return outcome
def _warm_one_inner(query_info: dict) -> str:
+ # Labels every outcome below, so the lane's cost is separable from the demand
+ # lane's in Grafana without re-deriving it from the selection.
+ lane = "preset" if query_info.get("preset_ids") else "demand"
team = teams.get(query_info["team_id"])
if team is None:
return "team_missing"
@@ -1020,7 +1298,7 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
# the selected shape's range in exactly the cases worth debugging.
query_info["_replay_date_from"] = (query_json.get("dateRange") or {}).get("date_from")
if runner is None:
- WARMING_QUERIES_COUNTER.labels(outcome="unsupported").inc()
+ WARMING_QUERIES_COUNTER.labels(lane=lane, outcome="unsupported").inc()
return "unsupported"
# Raw-path replays keep the pre-widening demand bar: a lazy-eligible
@@ -1032,14 +1310,19 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
# representative variant's own demand, not the shape-wide sum: raw
# replays aren't shared across variants, so a rarely-run expensive
# variant must not inherit a popular sibling's count.
- if not lazy_eligible and query_info.get("representative_query_count", 0) < RAW_REPLAY_MIN_QUERY_COUNT:
- WARMING_QUERIES_COUNTER.labels(outcome="skipped_raw_low_demand").inc()
+ raw_floor = (
+ PRESET_RAW_REPLAY_MIN_QUERY_COUNT
+ if lane == "preset" and query_info.get("representative_preset_tagged")
+ else RAW_REPLAY_MIN_QUERY_COUNT
+ )
+ if not lazy_eligible and query_info.get("representative_query_count", 0) < raw_floor:
+ WARMING_QUERIES_COUNTER.labels(lane=lane, outcome="skipped_raw_low_demand").inc()
return "skipped_raw_low_demand"
cache_key = runner.get_cache_key()
with seen_lock:
if (team.pk, cache_key) in seen_cache_keys:
- WARMING_QUERIES_COUNTER.labels(outcome="skipped_duplicate").inc()
+ WARMING_QUERIES_COUNTER.labels(lane=lane, outcome="skipped_duplicate").inc()
return "skipped_duplicate"
seen_cache_keys.add((team.pk, cache_key))
@@ -1051,10 +1334,10 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
# doesn't. refresh keeps the warm set fresh without paying for cold
# builds; backfill expands coverage without re-touching the warm set.
if mode == "refresh" and freshness is None:
- WARMING_QUERIES_COUNTER.labels(outcome="skipped_cold").inc()
+ WARMING_QUERIES_COUNTER.labels(lane=lane, outcome="skipped_cold").inc()
return "skipped_cold"
if mode == "backfill" and freshness is not None:
- WARMING_QUERIES_COUNTER.labels(outcome="skipped_already_warmed").inc()
+ WARMING_QUERIES_COUNTER.labels(lane=lane, outcome="skipped_already_warmed").inc()
return "skipped_already_warmed"
# The probe answers from Redis alone: S3-backed entries carry last_refresh in the
@@ -1067,9 +1350,20 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
else None
)
if not runner._is_stale(aged_refresh):
- WARMING_QUERIES_COUNTER.labels(outcome="skipped_fresh").inc()
+ WARMING_QUERIES_COUNTER.labels(lane=lane, outcome="skipped_fresh").inc()
return "skipped_fresh"
+ # A raw replay is a full live query, so the lane's low floor alone would let one
+ # team turn a handful of preset loads into hundreds of hourly scans. Budget is
+ # consumed here, after every skip gate, so fresh or duplicate shapes don't burn it.
+ if lane == "preset" and not lazy_eligible:
+ with seen_lock:
+ used = raw_preset_replays_by_team.get(team.pk, 0)
+ if used >= PRESET_LANE_MAX_RAW_SHAPES_PER_TEAM:
+ WARMING_QUERIES_COUNTER.labels(lane=lane, outcome="skipped_raw_over_budget").inc()
+ return "skipped_raw_over_budget"
+ raw_preset_replays_by_team[team.pk] = used + 1
+
# TODO: We shouldn't try to run a query if it failed last run
# Blocking-always, not the stale-checking default: run() re-checks
# staleness internally against the entry's true last_refresh, so a
@@ -1089,7 +1383,7 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
if attempt == WARMING_CAPACITY_RETRIES:
raise
time.sleep(random.uniform(*WARMING_CAPACITY_BACKOFF_RANGE_SECONDS))
- WARMING_QUERIES_COUNTER.labels(outcome="warmed").inc()
+ WARMING_QUERIES_COUNTER.labels(lane=lane, outcome="warmed").inc()
return "warmed"
except Exception as e:
# A team deleted after the teams dict was loaded (the 14-day demand
@@ -1112,7 +1406,7 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
normalized_query_hash=query_info["normalized_query_hash"],
)
capture_exception(e)
- WARMING_QUERIES_COUNTER.labels(outcome="failed").inc()
+ WARMING_QUERIES_COUNTER.labels(lane=lane, outcome="failed").inc()
return "failed"
finally:
# Pool threads hold their own Django connections; drop expired ones so
@@ -1274,15 +1568,20 @@ def report_warming_plan_op(context: dagster.OpExecutionContext, queries: list[di
total_underlying_requests = sum(q["query_count"] for q in queries)
median_shapes = statistics.median(shape_counts) if shape_counts else 0
+ preset_stats = _summarize_preset_lane(queries)
+
context.log.info(
f"DRY RUN — would warm {len(queries)} query shapes across {len(per_team)} teams "
f"(~{total_underlying_requests} underlying requests over the warming window). "
+ f"Of those, {preset_stats['preset_shape_count']} shapes come from "
+ f"{preset_stats['presets_selected']} saved presets across {preset_stats['preset_team_count']} teams. "
f"Per-team shapes: max={shape_counts[0] if shape_counts else 0}, median={median_shapes}. "
f"Top teams by shape count: {per_team[:10]}"
)
context.add_output_metadata(
{
"dry_run": True,
+ **preset_stats,
"team_count": len(per_team),
"total_query_shapes_to_warm": len(queries),
"total_underlying_requests": total_underlying_requests,
diff --git a/products/web_analytics/dags/tests/test_cache_warming.py b/products/web_analytics/dags/tests/test_cache_warming.py
index b6335309468c..85a31ce5c7d8 100644
--- a/products/web_analytics/dags/tests/test_cache_warming.py
+++ b/products/web_analytics/dags/tests/test_cache_warming.py
@@ -1,6 +1,7 @@
import gzip
import json
import threading
+from datetime import datetime, timedelta
from types import SimpleNamespace
from posthog.test.base import BaseTest
@@ -15,11 +16,15 @@ from posthog.clickhouse.query_tagging import Feature, get_query_tags, reset_quer
from posthog.exceptions import ClickHouseAtCapacity
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models import Team
+from posthog.models.instance_setting import override_instance_config
from posthog.query_cache import EntryFreshness
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import is_background_warming_request
+from products.web_analytics.backend.models.web_analytics_filter_preset import WebAnalyticsFilterPreset
from products.web_analytics.dags import cache_warming
from products.web_analytics.dags.cache_warming import (
+ PRESET_LANE_MAX_PRESETS_PER_TEAM,
+ PRESET_LANE_MAX_SHAPES_PER_PRESET,
WarmQueriesConfig,
build_replay_runner,
canonicalize_lazy_replay_json,
@@ -542,6 +547,153 @@ class TestFleetQuerySelection(BaseTest):
self.assertIsInstance(entry["normalized_query_hash"], int)
+class TestPresetLane(BaseTest):
+ """The preset lane selects shapes a team ran under a saved filter preset, below the
+ demand floor. Everything here guards the two things that keeps honest: only real
+ presets count, and the lane stays bounded."""
+
+ LAST_SEEN = datetime(2026, 8, 19, 12, 0, 0)
+
+ def _preset(self, short_id: str, team: Team | None = None, deleted: bool = False) -> WebAnalyticsFilterPreset:
+ return WebAnalyticsFilterPreset.objects.create(
+ team=team or self.team, short_id=short_id, name=short_id, deleted=deleted
+ )
+
+ def _row(
+ self,
+ preset_ids: list[str],
+ query_count: int = 1,
+ team_id: int | None = None,
+ shape: str = "s",
+ last_seen: datetime | None = None,
+ representative_tagged: bool = True,
+ ) -> tuple:
+ return (
+ team_id or self.team.pk,
+ json.dumps({"kind": "WebOverviewQuery", "properties": [{"key": shape}]}),
+ query_count,
+ query_count,
+ f"hash-{shape}",
+ ["-7d"],
+ preset_ids,
+ last_seen or self.LAST_SEEN,
+ representative_tagged,
+ )
+
+ def _select(self, rows: list[tuple], minimum_query_count: int = 5) -> list[dict]:
+ with patch("products.web_analytics.dags.cache_warming.sync_execute", return_value=rows):
+ return queries_to_keep_fresh(
+ dagster.build_op_context(),
+ days=7,
+ minimum_query_count=minimum_query_count,
+ max_shapes=1000,
+ preset_lane=True,
+ )
+
+ def test_preset_sql_bounds_ids_and_caps_priority(self) -> None:
+ # The id merge across ignored-field variants must stay bounded (an unbounded
+ # arrayDistinct(arrayFlatten(...)) let one shape carry an attacker-sized id array
+ # into validation), and preset priority must stop at the lane's per-team budget so
+ # unvalidated tagged rows can't evict a team's real hot shapes from the selection.
+ with patch("products.web_analytics.dags.cache_warming.sync_execute", return_value=[]) as mock_exec:
+ queries_to_keep_fresh(
+ dagster.build_op_context(),
+ days=7,
+ minimum_query_count=5,
+ max_shapes=1000,
+ preset_lane=True,
+ )
+ sql = mock_exec.call_args[0][0]
+ self.assertIn("groupUniqArrayArray", sql)
+ self.assertNotIn("arrayFlatten", sql)
+ self.assertIn("preset_priority DESC", sql)
+ self.assertIn("row_number() OVER", sql)
+
+ def test_preset_shape_survives_below_the_demand_floor(self) -> None:
+ # The reason the lane exists: exploration rarely runs often enough to clear the
+ # floor, so without this a saved preset stays permanently cold.
+ self._preset("abc123")
+
+ result = self._select([self._row(["abc123"], query_count=1, shape="tagged"), self._row([], query_count=1)])
+
+ self.assertEqual([row["query_json"]["properties"][0]["key"] for row in result], ["tagged"])
+ self.assertEqual(result[0]["preset_ids"], ["abc123"])
+
+ @parameterized.expand(
+ [
+ ("deleted", "deleted"),
+ ("other_team", "other_team"),
+ ("never_existed", "never_existed"),
+ ]
+ )
+ def test_unusable_preset_id_falls_back_to_the_demand_floor(self, _name: str, kind: str) -> None:
+ # The preset id reaches us from the client's query tags, so a shape may only skip
+ # the demand floor once Postgres agrees the preset is real, live, and this team's.
+ if kind == "deleted":
+ self._preset("abc123", deleted=True)
+ elif kind == "other_team":
+ self._preset("abc123", team=Team.objects.create(organization=self.organization))
+
+ below_floor = self._select([self._row(["abc123"], query_count=1)])
+ self.assertEqual(below_floor, [])
+
+ # Same shape, now with real demand: it comes back as a plain demand-lane shape,
+ # so the id was ignored rather than the row blacklisted.
+ above_floor = self._select([self._row(["abc123"], query_count=50)])
+ self.assertEqual([row["preset_ids"] for row in above_floor], [[]])
+
+ def test_teams_keep_their_most_recently_used_presets(self) -> None:
+ # A team with more presets than the cap keeps the ones it actually opens. Recency
+ # comes from the scan, not the model's last_modified_at, which only tracks edits.
+ over_cap = PRESET_LANE_MAX_PRESETS_PER_TEAM + 1
+ for index in range(over_cap):
+ self._preset(f"preset{index}")
+ rows = [
+ self._row(
+ [f"preset{index}"],
+ query_count=1,
+ shape=f"s{index}",
+ # preset0 is the stalest, so it is the one that must drop.
+ last_seen=self.LAST_SEEN - timedelta(days=over_cap - index),
+ )
+ for index in range(over_cap)
+ ]
+
+ result = self._select(rows)
+
+ kept = {pid for row in result for pid in row["preset_ids"]}
+ self.assertEqual(len(kept), PRESET_LANE_MAX_PRESETS_PER_TEAM)
+ self.assertNotIn("preset0", kept)
+
+ def test_one_preset_cannot_mint_unbounded_shapes(self) -> None:
+ # Without this a single preset left open across every tab and breakdown would
+ # claim hourly background compute for hundreds of shapes.
+ self._preset("abc123")
+ over_cap = PRESET_LANE_MAX_SHAPES_PER_PRESET + 15
+ rows = [self._row(["abc123"], query_count=1, shape=f"s{index}") for index in range(over_cap)]
+
+ result = self._select(rows)
+
+ self.assertEqual(len(result), PRESET_LANE_MAX_SHAPES_PER_PRESET)
+
+ def test_lane_off_leaves_the_selection_alone(self) -> None:
+ # With the lane off the selection must be exactly what it was before it existed —
+ # no preset columns read, no shape kept below the floor.
+ rows = [
+ (self.team.pk, '{"kind": "WebOverviewQuery"}', 1, 1, "hash-a", ["-7d"]),
+ (self.team.pk, '{"kind": "WebGoalsQuery"}', 50, 50, "hash-b", ["-7d"]),
+ ]
+ with patch("products.web_analytics.dags.cache_warming.sync_execute", return_value=rows) as mock_exec:
+ result = queries_to_keep_fresh(
+ dagster.build_op_context(), days=7, minimum_query_count=5, max_shapes=1000, preset_lane=False
+ )
+
+ # No Python-side floor is applied when the lane is off — the SQL's HAVING does it.
+ self.assertEqual(len(result), 2)
+ self.assertNotIn("preset_ids", result[0])
+ self.assertNotIn("notEmpty(preset_ids)", mock_exec.call_args[0][0])
+
+
class _FakeObjectStorage:
def __init__(self) -> None:
self.store: dict[str, bytes] = {}
@@ -569,6 +721,23 @@ class TestWarmableQueriesCaching(BaseTest):
self.assertEqual(first, second)
self.assertEqual(first[0]["team_id"], 101)
+ @patch("products.web_analytics.dags.cache_warming.object_storage", new_callable=_FakeObjectStorage)
+ @patch("products.web_analytics.dags.cache_warming.sync_execute")
+ def test_toggling_the_preset_lane_misses_the_cache(
+ self, mock_exec: MagicMock, _storage: _FakeObjectStorage
+ ) -> None:
+ # The selection is cached for hours, so unless the preset lane flag is part of the
+ # cache key, turning it off keeps serving preset shapes until the TTL expires and
+ # the kill switch is cosmetic exactly when it is needed.
+ mock_exec.return_value = [(101, '{"kind": "WebOverviewQuery"}', 50, 50, 123, ["-7d"], [], None, False)]
+
+ with override_instance_config("WEB_ANALYTICS_WARMING_PRESET_LANE_ENABLED", True):
+ get_warmable_queries_op(dagster.build_op_context())
+ with override_instance_config("WEB_ANALYTICS_WARMING_PRESET_LANE_ENABLED", False):
+ get_warmable_queries_op(dagster.build_op_context())
+
+ self.assertEqual(mock_exec.call_count, 2)
+
@patch("products.web_analytics.dags.cache_warming.object_storage")
@patch("products.web_analytics.dags.cache_warming.sync_execute")
def test_storage_failure_falls_back_to_scan(self, mock_exec: MagicMock, mock_storage: MagicMock) -> None:
@@ -601,13 +770,26 @@ class TestWarmQueriesOp(BaseTest):
# A raw-path (not lazy-eligible) shape below the demand bar must not
# replay: an expensive ineligible shape would otherwise become an
# hourly background scan outside the tenant's request throttles.
- ("raw_low_demand_skipped", False, 2, 0),
- ("raw_high_demand_warms", False, 10, 1),
- ("lazy_low_demand_warms", True, 2, 1),
+ ("raw_low_demand_skipped", False, 2, [], False, 0),
+ ("raw_high_demand_warms", False, 10, [], False, 1),
+ ("lazy_low_demand_warms", True, 2, [], False, 1),
+ # A preset shape gets a lower raw floor, not a bypass: a preset with a
+ # conversion goal is raw-only, so at the demand floor it would never warm.
+ ("preset_raw_at_lower_floor_warms", False, 2, ["abc123"], True, 1),
+ ("preset_raw_below_lower_floor_skipped", False, 1, ["abc123"], True, 0),
+ # Raw replays are not shared across variants, so a tagged sibling must not
+ # lower the bar for an untagged representative.
+ ("preset_raw_untagged_representative_keeps_full_floor", False, 2, ["abc123"], False, 0),
]
)
def test_raw_replays_keep_higher_demand_bar(
- self, _name: str, lazy_eligible: bool, representative_query_count: int, expected_runs: int
+ self,
+ _name: str,
+ lazy_eligible: bool,
+ representative_query_count: int,
+ preset_ids: list[str],
+ representative_preset_tagged: bool,
+ expected_runs: int,
) -> None:
runner = MagicMock()
runner.get_cache_key.return_value = f"key-{_name}"
@@ -632,12 +814,48 @@ class TestWarmQueriesOp(BaseTest):
"query_count": 999,
"representative_query_count": representative_query_count,
"normalized_query_hash": "h",
+ "preset_ids": preset_ids,
+ "representative_preset_tagged": representative_preset_tagged,
}
],
)
self.assertEqual(runner.run.call_count, expected_runs)
+ def test_raw_preset_replays_are_budgeted_per_team(self) -> None:
+ # Valid preset ids prove membership, not that the query matches the preset, so
+ # without the budget a team member could tag arbitrary expensive raw-only shapes
+ # and have every one replayed hourly.
+ runner = MagicMock()
+ runner.get_cache_key.side_effect = lambda: f"key-{runner.get_cache_key.call_count}"
+ with (
+ patch(
+ "products.web_analytics.dags.cache_warming.build_replay_runner",
+ return_value=(runner, {}, False),
+ ),
+ patch("products.web_analytics.dags.cache_warming.QueryCache") as mock_cm,
+ patch("products.web_analytics.dags.cache_warming.PRESET_LANE_MAX_RAW_SHAPES_PER_TEAM", 2),
+ ):
+ mock_cm.return_value.freshness.return_value = None
+ warm_queries_op(
+ dagster.build_op_context(),
+ WarmQueriesConfig(),
+ [
+ {
+ "team_id": self.team.pk,
+ "query_json": {"kind": "WebOverviewQuery", "properties": [{"key": str(i)}]},
+ "query_count": 999,
+ "representative_query_count": 999,
+ "normalized_query_hash": f"h{i}",
+ "preset_ids": ["abc123"],
+ "representative_preset_tagged": True,
+ }
+ for i in range(3)
+ ],
+ )
+
+ self.assertEqual(runner.run.call_count, 2)
+
@parameterized.expand(
[
# The dagster CH user's simultaneous-query cap is shared with other
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8bd6289a32ff..607c5f431969 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1532,6 +1532,8 @@ export namespace Schemas {
export interface QueryLogTags {
/** Name of the query, preferably unique. For example web_analytics_vitals */
name?: string | null;
+ /** Short id of the saved Web analytics filter preset this query was run under, if any. */
+ presetId?: string | null;
/** Product responsible for this query. Use string, there's no need to churn the Schema when we add a new product * */
productKey?: string | null;
/** Scene where this query is shown in the UI. Use string, there's no need to churn the Schema when we add a new Scene * */