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(marketing-analytics): serve reads exclusively from precompute (#93048)

Lucas Ricoy11e10d7ba610
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f461dc5d285b..40423b2dbec7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9900,6 +9900,14 @@ snapshots:
hash: v1.k794b7964.a08eefe3f8b95c0cee0659fb050cd3114778edb6a3755fdfe7b95460e031e425.Sodxn6zMfktliL0TqxWRzmRFMPymrVZSrGH4ryLJKRc
scenes-app-marketing-analytics-dashboard-change-value-cell--unavailable--light:
hash: v1.k794b7964.077208274eef6634c72fb949f22e3cfc5ce4ee6ed110883744ddc6c598e2997c.8WkzjKlIOrwhI2hYPh3FKHnwWIsSzE39LASNS1SaTo8
+ scenes-app-marketing-analytics-freshness--behind--dark:
+ hash: v1.k794b7964.24e00c5991fdda65218358c71de110f4e94c84f483b6b550225da1bf405f1511.76cXtLdLAt40yxKRi1qT71n8DdikUm3oiMTL8IWwDwI
+ scenes-app-marketing-analytics-freshness--behind--light:
+ hash: v1.k794b7964.b2d8e1c949197fcff85a43871f4a08868e399426f5b0deed1836de54f5694a4a.iJ0Icp8ZeVBvNrPdrwS1Zbq4yUADXJxuyRWy2YKQdnY
+ scenes-app-marketing-analytics-freshness--fresh--dark:
+ hash: v1.k794b7964.71ad45e65a5513ff7088e026d8ffb2bf891fb1effddb0e9dbd95ba78b597c3b1.0e6bNu95d2bH_NlZmGGW7oiHJ__aHNSxqzRcxMUA4xM
+ scenes-app-marketing-analytics-freshness--fresh--light:
+ hash: v1.k794b7964.b8d9453c270c310350d2bcf30cdb54cae4da19b8877e8d3206160478eb2dda94.dJpt6MIMxg7mOxiHC6PoqwTGwMfiGrln7SheHTKHTcU
scenes-app-max-ai-logs-query-tool--no-matches--dark:
hash: v1.k794b7964.c231a64a00f6dfc8bf5b88c3dab624bad88d347b96be0b2e6b0cc14e1c10e1cc.ScE515QePrAYrJB-UWn5sakLt5cKxQKQQrx_n_uJERI
scenes-app-max-ai-logs-query-tool--no-matches--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 38fa7bb1c1b3..4e25c6f7759a 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -11954,6 +11954,10 @@
"description": "What triggered the calculation of the query, leave empty if user/immediate",
"type": "string"
},
+ "dataComputedAt": {
+ "description": "ISO timestamp of the oldest precompute window backing this result — surfaced as \"data as of X\".",
+ "type": "string"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -11977,6 +11981,10 @@
"format": "date-time",
"type": "string"
},
+ "precomputeNotReady": {
+ "description": "True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a \"computing\" state rather than empty results. Marketing analytics serves exclusively from precompute.",
+ "type": "boolean"
+ },
"query_metadata": {
"type": "object"
},
@@ -12487,6 +12495,10 @@
"items": {},
"type": "array"
},
+ "dataComputedAt": {
+ "description": "ISO timestamp of the oldest precompute window backing this result — surfaced as \"data as of X\".",
+ "type": "string"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -12519,6 +12531,10 @@
"offset": {
"$ref": "#/definitions/integer"
},
+ "precomputeNotReady": {
+ "description": "True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a \"computing\" state rather than empty results. Marketing analytics serves exclusively from precompute.",
+ "type": "boolean"
+ },
"query_metadata": {
"type": "object"
},
@@ -19211,6 +19227,10 @@
"items": {},
"type": "array"
},
+ "dataComputedAt": {
+ "description": "ISO timestamp of the oldest precompute window backing this result — surfaced as \"data as of X\".",
+ "type": "string"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -19232,6 +19252,10 @@
"offset": {
"$ref": "#/definitions/integer"
},
+ "precomputeNotReady": {
+ "description": "True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a \"computing\" state rather than empty results. Marketing analytics serves exclusively from precompute.",
+ "type": "boolean"
+ },
"query_status": {
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
@@ -19295,6 +19319,10 @@
{
"additionalProperties": false,
"properties": {
+ "dataComputedAt": {
+ "description": "ISO timestamp of the oldest precompute window backing this result — surfaced as \"data as of X\".",
+ "type": "string"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -19307,6 +19335,10 @@
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
},
+ "precomputeNotReady": {
+ "description": "True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a \"computing\" state rather than empty results. Marketing analytics serves exclusively from precompute.",
+ "type": "boolean"
+ },
"query_status": {
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
@@ -34269,6 +34301,10 @@
"MarketingAnalyticsAggregatedQueryResponse": {
"additionalProperties": false,
"properties": {
+ "dataComputedAt": {
+ "description": "ISO timestamp of the oldest precompute window backing this result — surfaced as \"data as of X\".",
+ "type": "string"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -34281,6 +34317,10 @@
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
},
+ "precomputeNotReady": {
+ "description": "True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a \"computing\" state rather than empty results. Marketing analytics serves exclusively from precompute.",
+ "type": "boolean"
+ },
"query_status": {
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
@@ -35479,6 +35519,10 @@
"items": {},
"type": "array"
},
+ "dataComputedAt": {
+ "description": "ISO timestamp of the oldest precompute window backing this result — surfaced as \"data as of X\".",
+ "type": "string"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -35500,6 +35544,10 @@
"offset": {
"$ref": "#/definitions/integer"
},
+ "precomputeNotReady": {
+ "description": "True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a \"computing\" state rather than empty results. Marketing analytics serves exclusively from precompute.",
+ "type": "boolean"
+ },
"query_status": {
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
@@ -42784,6 +42832,10 @@
"items": {},
"type": "array"
},
+ "dataComputedAt": {
+ "description": "ISO timestamp of the oldest precompute window backing this result — surfaced as \"data as of X\".",
+ "type": "string"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -42805,6 +42857,10 @@
"offset": {
"$ref": "#/definitions/integer"
},
+ "precomputeNotReady": {
+ "description": "True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a \"computing\" state rather than empty results. Marketing analytics serves exclusively from precompute.",
+ "type": "boolean"
+ },
"query_status": {
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
@@ -42868,6 +42924,10 @@
{
"additionalProperties": false,
"properties": {
+ "dataComputedAt": {
+ "description": "ISO timestamp of the oldest precompute window backing this result — surfaced as \"data as of X\".",
+ "type": "string"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -42880,6 +42940,10 @@
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
},
+ "precomputeNotReady": {
+ "description": "True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a \"computing\" state rather than empty results. Marketing analytics serves exclusively from precompute.",
+ "type": "boolean"
+ },
"query_status": {
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
@@ -44289,6 +44353,10 @@
"items": {},
"type": "array"
},
+ "dataComputedAt": {
+ "description": "ISO timestamp of the oldest precompute window backing this result — surfaced as \"data as of X\".",
+ "type": "string"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -44310,6 +44378,10 @@
"offset": {
"$ref": "#/definitions/integer"
},
+ "precomputeNotReady": {
+ "description": "True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a \"computing\" state rather than empty results. Marketing analytics serves exclusively from precompute.",
+ "type": "boolean"
+ },
"query_status": {
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
@@ -44373,6 +44445,10 @@
{
"additionalProperties": false,
"properties": {
+ "dataComputedAt": {
+ "description": "ISO timestamp of the oldest precompute window backing this result — surfaced as \"data as of X\".",
+ "type": "string"
+ },
"error": {
"description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
"type": "string"
@@ -44385,6 +44461,10 @@
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
},
+ "precomputeNotReady": {
+ "description": "True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a \"computing\" state rather than empty results. Marketing analytics serves exclusively from precompute.",
+ "type": "boolean"
+ },
"query_status": {
"$ref": "#/definitions/QueryStatus",
"description": "Query status indicates whether next to the provided data, a query is still running."
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 744d3ea6aee5..07262fd73809 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -7704,6 +7704,11 @@ export interface MarketingAnalyticsTableQueryResponse extends AnalyticsQueryResp
hasMore?: boolean
limit?: integer
offset?: integer
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a
+ * "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string
}
export type CachedMarketingAnalyticsTableQueryResponse = CachedQueryResponse<MarketingAnalyticsTableQueryResponse>
@@ -7712,6 +7717,11 @@ export interface MarketingAnalyticsAggregatedQueryResponse extends AnalyticsQuer
results: Record<string, MarketingAnalyticsItem>
hogql?: string
samplingRate?: SamplingRate
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a
+ * "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string
}
export type CachedMarketingAnalyticsAggregatedQueryResponse =
diff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsFreshness.stories.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsFreshness.stories.tsx
new file mode 100644
index 000000000000..753cb20cbd89
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsFreshness.stories.tsx
@@ -0,0 +1,22 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { dayjs } from 'lib/dayjs'
+
+import { MarketingAnalyticsFreshness } from './MarketingAnalyticsFreshness'
+
+type Story = StoryObj<typeof MarketingAnalyticsFreshness>
+const meta: Meta<typeof MarketingAnalyticsFreshness> = {
+ title: 'Scenes-App/Marketing Analytics/Freshness',
+ component: MarketingAnalyticsFreshness,
+ tags: ['autodocs'],
+}
+export default meta
+
+// Within the ~2h refresh window: neutral clock badge.
+export const Fresh: Story = { args: { computedAt: dayjs().subtract(20, 'minute').toISOString() } }
+
+// Older than the refresh window (warmer behind): warning badge.
+export const Behind: Story = { args: { computedAt: dayjs().subtract(5, 'hour').toISOString() } }
+
+// No precompute freshness known: renders nothing, so there is nothing to snapshot.
+export const Unknown: Story = { args: { computedAt: null }, tags: ['test-skip'] }
diff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsFreshness.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsFreshness.tsx
new file mode 100644
index 000000000000..089de6c47934
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsFreshness.tsx
@@ -0,0 +1,50 @@
+import { IconClock, IconWarning } from '@posthog/icons'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { dayjs } from 'lib/dayjs'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+
+// Marketing analytics serves from precomputed data refreshed by the hourly warmer, so the numbers can
+// trail live by up to ~2 hours. Past that the warmer is likely behind, so the badge switches to a warning.
+const STALE_WARNING_HOURS = 2
+
+export function MarketingAnalyticsFreshness({ computedAt }: { computedAt: string | null }): JSX.Element | null {
+ if (!computedAt) {
+ return null
+ }
+
+ const behindByHours = dayjs().diff(dayjs(computedAt), 'hour')
+ const isBehind = behindByHours >= STALE_WARNING_HOURS
+
+ return (
+ <Tooltip
+ title={
+ <div className="flex flex-col gap-1">
+ <span>
+ {isBehind
+ ? 'Marketing analytics refreshes about once an hour. This data is older than that, so the refresh is running behind.'
+ : 'Marketing analytics refreshes about once an hour, so numbers can be up to 2 hours old.'}
+ </span>
+ <div className="flex items-center gap-1">
+ <span>Data from</span>
+ <TZLabel time={computedAt} showPopover={false} />
+ </div>
+ </div>
+ }
+ >
+ <LemonButton
+ icon={isBehind ? <IconWarning /> : <IconClock />}
+ status={isBehind ? 'danger' : 'default'}
+ type="secondary"
+ size="small"
+ // Informational only: keep it out of the tab order but labelled for screen readers.
+ tabIndex={-1}
+ aria-label="Marketing analytics data freshness"
+ data-attr="marketing-analytics-freshness"
+ >
+ Updated hourly
+ </LemonButton>
+ </Tooltip>
+ )
+}
diff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsNotReady.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsNotReady.tsx
new file mode 100644
index 000000000000..da73214be79e
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsNotReady.tsx
@@ -0,0 +1,10 @@
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+
+export function MarketingAnalyticsNotReady(): JSX.Element {
+ return (
+ <LemonBanner type="info" data-attr="marketing-analytics-not-ready">
+ Your marketing analytics is being prepared. This report refreshes about once an hour, so it should appear
+ shortly. Check back in a few minutes.
+ </LemonBanner>
+ )
+}
diff --git a/frontend/src/scenes/marketing-analytics/useMarketingAnalyticsPrecompute.ts b/frontend/src/scenes/marketing-analytics/useMarketingAnalyticsPrecompute.ts
new file mode 100644
index 000000000000..feddd84d0740
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/useMarketingAnalyticsPrecompute.ts
@@ -0,0 +1,38 @@
+import { useValues } from 'kea'
+
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'
+import { DataNode } from '~/queries/schema/schema-general'
+import { InsightLogicProps } from '~/types'
+
+export interface MarketingAnalyticsPrecomputeStatus {
+ /** The window this read asked for has not been warmed yet. */
+ notReady: boolean
+ /** ISO timestamp of the oldest precompute window behind the result, or null when nothing was read. */
+ computedAt: string | null
+}
+
+/** The precompute-only signals a marketing analytics response carries.
+ *
+ * Marketing analytics serves exclusively from precompute, so a cold window comes back as an empty result
+ * with `precomputeNotReady` set — a tile that only looks at the rows cannot tell that apart from a team
+ * with no spend. Binds the same dataNodeLogic instance the tile's own DataTable builds, so the query
+ * still loads once. */
+export function useMarketingAnalyticsPrecompute(
+ source: DataNode,
+ insightProps: InsightLogicProps
+): MarketingAnalyticsPrecomputeStatus {
+ const { response, responseLoading } = useValues(
+ dataNodeLogic({
+ query: source,
+ key: insightVizDataNodeKey(insightProps),
+ dataNodeCollectionId: insightProps.dataNodeCollectionId,
+ })
+ )
+ const precomputeResponse = response as { precomputeNotReady?: boolean; dataComputedAt?: string } | null
+
+ return {
+ notReady: !responseLoading && precomputeResponse?.precomputeNotReady === true,
+ computedAt: precomputeResponse?.dataComputedAt ?? null,
+ }
+}
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview.tsx
index 05db989de3bf..2b88978b92f6 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview.tsx
@@ -12,6 +12,7 @@ import {
MarketingAnalyticsAggregatedQueryResponse,
} from '~/queries/schema/schema-general'
import { QueryContext } from '~/queries/types'
+import { MarketingAnalyticsNotReady } from '~/scenes/marketing-analytics/MarketingAnalyticsNotReady'
import { marketingAnalyticsSettingsLogic } from '../../logic/marketingAnalyticsSettingsLogic'
import {
@@ -72,6 +73,12 @@ export function MarketingAnalyticsOverview(props: {
return <InsightErrorState title={responseError} />
}
+ // A cold precompute window comes back as an empty result, which the metric grid would render as a row
+ // of blanks. Say it is still being prepared instead.
+ if (!responseLoading && marketingOverviewQueryResponse?.precomputeNotReady) {
+ return <MarketingAnalyticsNotReady />
+ }
+
// Combine validation warnings with any backend warnings (e.g. skipped conversion goals)
const allWarnings = [
...(validationWarnings ?? []),
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsTable/MarketingAnalyticsTable.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsTable/MarketingAnalyticsTable.tsx
index 930d84d5a45b..c8a13619ec9a 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsTable/MarketingAnalyticsTable.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsTable/MarketingAnalyticsTable.tsx
@@ -19,6 +19,9 @@ import {
MarketingAnalyticsTableQuery,
} from '~/queries/schema/schema-general'
import { QueryContext, QueryContextColumn } from '~/queries/types'
+import { MarketingAnalyticsFreshness } from '~/scenes/marketing-analytics/MarketingAnalyticsFreshness'
+import { MarketingAnalyticsNotReady } from '~/scenes/marketing-analytics/MarketingAnalyticsNotReady'
+import { useMarketingAnalyticsPrecompute } from '~/scenes/marketing-analytics/useMarketingAnalyticsPrecompute'
import { webAnalyticsDataTableQueryContext } from '~/scenes/web-analytics/tiles/WebAnalyticsTile'
import { InsightLogicProps } from '~/types'
@@ -50,6 +53,7 @@ export const MarketingAnalyticsTable = ({
const { drillDownLevel, nativeSourcesHierarchyStatus } = useValues(marketingAnalyticsLogic)
const hasExtendedDrillDown = useFeatureFlag('MARKETING_ANALYTICS_EXTENDED_DRILL_DOWN')
const { conversion_goals } = useValues(marketingAnalyticsSettingsLogic)
+ const { notReady: precomputeNotReady, computedAt } = useMarketingAnalyticsPrecompute(query.source, insightProps)
const [searchTerm, setSearchTerm] = useState('')
@@ -115,7 +119,7 @@ export const MarketingAnalyticsTable = ({
return (
<div className="bg-surface-primary">
<div className="p-4 border-b border-border bg-bg-light">
- <div className="flex gap-4 justify-between items-center">
+ <div className="flex flex-wrap gap-4 justify-between items-center">
<div className="flex items-center gap-2">
<LemonInput
type="search"
@@ -191,9 +195,12 @@ export const MarketingAnalyticsTable = ({
<IconInfo className="text-xl text-secondary" />
</Tooltip>
</div>
- <LemonButton type="secondary" icon={<IconGear />} onClick={showColumnConfigModal}>
- Configure columns
- </LemonButton>
+ <div className="flex items-center gap-2">
+ <MarketingAnalyticsFreshness computedAt={computedAt} />
+ <LemonButton type="secondary" icon={<IconGear />} onClick={showColumnConfigModal}>
+ Configure columns
+ </LemonButton>
+ </div>
</div>
</div>
{validationWarnings && validationWarnings.length > 0 && (
@@ -210,15 +217,21 @@ export const MarketingAnalyticsTable = ({
/>
</div>
)}
- <div className="relative marketing-analytics-table-container">
- <Query
- attachTo={attachTo}
- query={query}
- readOnly={false}
- context={marketingAnalyticsContext}
- setQuery={setQuery}
- />
- </div>
+ {precomputeNotReady ? (
+ <div className="p-4">
+ <MarketingAnalyticsNotReady />
+ </div>
+ ) : (
+ <div className="relative marketing-analytics-table-container">
+ <Query
+ attachTo={attachTo}
+ query={query}
+ readOnly={false}
+ context={marketingAnalyticsContext}
+ setQuery={setQuery}
+ />
+ </div>
+ )}
<MarketingAnalyticsColumnConfigModal query={query} />
</div>
)
diff --git a/posthog/schema.py b/posthog/schema.py
index 8958578938c4..9d0602e0a8b7 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -13358,6 +13358,10 @@ class CachedMarketingAnalyticsAggregatedQueryResponse(BaseModel):
default=None,
description=("What triggered the calculation of the query, leave empty if user/immediate"),
)
+ dataComputedAt: str | None = Field(
+ default=None,
+ description=('ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X".'),
+ )
error: str | None = Field(
default=None,
description=(
@@ -13369,6 +13373,14 @@ class CachedMarketingAnalyticsAggregatedQueryResponse(BaseModel):
last_refresh: AwareDatetime
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
next_allowed_client_refresh: AwareDatetime
+ precomputeNotReady: bool | None = Field(
+ default=None,
+ description=(
+ "True when a conversion goal's precompute has not been warmed for this"
+ ' window yet — the UI shows a "computing" state rather than empty results.'
+ " Marketing analytics serves exclusively from precompute."
+ ),
+ )
query_metadata: dict[str, Any] | None = None
query_scan: QueryScanSummary | None = Field(
default=None,
@@ -13671,6 +13683,10 @@ class CachedMarketingAnalyticsTableQueryResponse(BaseModel):
description=("What triggered the calculation of the query, leave empty if user/immediate"),
)
columns: list | None = None
+ dataComputedAt: str | None = Field(
+ default=None,
+ description=('ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X".'),
+ )
error: str | None = Field(
default=None,
description=(
@@ -13685,6 +13701,14 @@ class CachedMarketingAnalyticsTableQueryResponse(BaseModel):
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
next_allowed_client_refresh: AwareDatetime
offset: int | None = None
+ precomputeNotReady: bool | None = Field(
+ default=None,
+ description=(
+ "True when a conversion goal's precompute has not been warmed for this"
+ ' window yet — the UI shows a "computing" state rather than empty results.'
+ " Marketing analytics serves exclusively from precompute."
+ ),
+ )
query_metadata: dict[str, Any] | None = None
query_scan: QueryScanSummary | None = Field(
default=None,
@@ -16663,6 +16687,10 @@ class Response12(BaseModel):
extra="forbid",
)
columns: list | None = None
+ dataComputedAt: str | None = Field(
+ default=None,
+ description=('ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X".'),
+ )
error: str | None = Field(
default=None,
description=(
@@ -16674,6 +16702,14 @@ class Response12(BaseModel):
limit: int | None = None
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int | None = None
+ precomputeNotReady: bool | None = Field(
+ default=None,
+ description=(
+ "True when a conversion goal's precompute has not been warmed for this"
+ ' window yet — the UI shows a "computing" state rather than empty results.'
+ " Marketing analytics serves exclusively from precompute."
+ ),
+ )
query_status: QueryStatus | None = Field(
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
@@ -16715,6 +16751,10 @@ class Response13(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ dataComputedAt: str | None = Field(
+ default=None,
+ description=('ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X".'),
+ )
error: str | None = Field(
default=None,
description=(
@@ -16723,6 +16763,14 @@ class Response13(BaseModel):
)
hogql: str | None = Field(default=None, description="Generated HogQL query.")
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ precomputeNotReady: bool | None = Field(
+ default=None,
+ description=(
+ "True when a conversion goal's precompute has not been warmed for this"
+ ' window yet — the UI shows a "computing" state rather than empty results.'
+ " Marketing analytics serves exclusively from precompute."
+ ),
+ )
query_status: QueryStatus | None = Field(
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
@@ -19180,6 +19228,10 @@ class MarketingAnalyticsAggregatedQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ dataComputedAt: str | None = Field(
+ default=None,
+ description=('ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X".'),
+ )
error: str | None = Field(
default=None,
description=(
@@ -19188,6 +19240,14 @@ class MarketingAnalyticsAggregatedQueryResponse(BaseModel):
)
hogql: str | None = Field(default=None, description="Generated HogQL query.")
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ precomputeNotReady: bool | None = Field(
+ default=None,
+ description=(
+ "True when a conversion goal's precompute has not been warmed for this"
+ ' window yet — the UI shows a "computing" state rather than empty results.'
+ " Marketing analytics serves exclusively from precompute."
+ ),
+ )
query_status: QueryStatus | None = Field(
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
@@ -19433,6 +19493,10 @@ class MarketingAnalyticsTableQueryResponse(BaseModel):
extra="forbid",
)
columns: list | None = None
+ dataComputedAt: str | None = Field(
+ default=None,
+ description=('ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X".'),
+ )
error: str | None = Field(
default=None,
description=(
@@ -19444,6 +19508,14 @@ class MarketingAnalyticsTableQueryResponse(BaseModel):
limit: int | None = None
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int | None = None
+ precomputeNotReady: bool | None = Field(
+ default=None,
+ description=(
+ "True when a conversion goal's precompute has not been warmed for this"
+ ' window yet — the UI shows a "computing" state rather than empty results.'
+ " Marketing analytics serves exclusively from precompute."
+ ),
+ )
query_status: QueryStatus | None = Field(
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
@@ -20944,6 +21016,10 @@ class QueryResponseAlternative33(BaseModel):
extra="forbid",
)
columns: list | None = None
+ dataComputedAt: str | None = Field(
+ default=None,
+ description=('ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X".'),
+ )
error: str | None = Field(
default=None,
description=(
@@ -20955,6 +21031,14 @@ class QueryResponseAlternative33(BaseModel):
limit: int | None = None
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int | None = None
+ precomputeNotReady: bool | None = Field(
+ default=None,
+ description=(
+ "True when a conversion goal's precompute has not been warmed for this"
+ ' window yet — the UI shows a "computing" state rather than empty results.'
+ " Marketing analytics serves exclusively from precompute."
+ ),
+ )
query_status: QueryStatus | None = Field(
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
@@ -20996,6 +21080,10 @@ class QueryResponseAlternative34(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ dataComputedAt: str | None = Field(
+ default=None,
+ description=('ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X".'),
+ )
error: str | None = Field(
default=None,
description=(
@@ -21004,6 +21092,14 @@ class QueryResponseAlternative34(BaseModel):
)
hogql: str | None = Field(default=None, description="Generated HogQL query.")
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ precomputeNotReady: bool | None = Field(
+ default=None,
+ description=(
+ "True when a conversion goal's precompute has not been warmed for this"
+ ' window yet — the UI shows a "computing" state rather than empty results.'
+ " Marketing analytics serves exclusively from precompute."
+ ),
+ )
query_status: QueryStatus | None = Field(
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
@@ -21859,6 +21955,10 @@ class QueryResponseAlternative50(BaseModel):
extra="forbid",
)
columns: list | None = None
+ dataComputedAt: str | None = Field(
+ default=None,
+ description=('ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X".'),
+ )
error: str | None = Field(
default=None,
description=(
@@ -21870,6 +21970,14 @@ class QueryResponseAlternative50(BaseModel):
limit: int | None = None
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int | None = None
+ precomputeNotReady: bool | None = Field(
+ default=None,
+ description=(
+ "True when a conversion goal's precompute has not been warmed for this"
+ ' window yet — the UI shows a "computing" state rather than empty results.'
+ " Marketing analytics serves exclusively from precompute."
+ ),
+ )
query_status: QueryStatus | None = Field(
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
@@ -21911,6 +22019,10 @@ class QueryResponseAlternative51(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ dataComputedAt: str | None = Field(
+ default=None,
+ description=('ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X".'),
+ )
error: str | None = Field(
default=None,
description=(
@@ -21919,6 +22031,14 @@ class QueryResponseAlternative51(BaseModel):
)
hogql: str | None = Field(default=None, description="Generated HogQL query.")
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ precomputeNotReady: bool | None = Field(
+ default=None,
+ description=(
+ "True when a conversion goal's precompute has not been warmed for this"
+ ' window yet — the UI shows a "computing" state rather than empty results.'
+ " Marketing analytics serves exclusively from precompute."
+ ),
+ )
query_status: QueryStatus | None = Field(
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
index f69352e4fbc6..7c08793f0856 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -608,6 +608,16 @@ class LazyComputationResult:
# be cached. Serving live once and letting the next request use the jobs is the
# intended reaction.
freshly_built: bool = False
+ # Oldest `computed_at` across the served jobs — the moment the stalest window in the
+ # range was last materialized. None when nothing was served (not ready) or a served
+ # job predates the column. Callers surface it as "data as of X".
+ computed_at: datetime | None = None
+
+
+def _oldest_computed_at(jobs: list[PreaggregationJob]) -> datetime | None:
+ """Oldest `computed_at` among served jobs — the stalest window bounds how old the data can be."""
+ stamps = [j.computed_at for j in jobs if j.computed_at is not None]
+ return min(stamps) if stamps else None
def compute_query_hash(query_info: LazyComputationQuery) -> str:
@@ -1206,6 +1216,7 @@ class LazyComputationExecutor:
ready=True,
job_ids=[j.id for j in covering],
stale=True,
+ computed_at=_oldest_computed_at(covering),
)
_log_execution("stale_hit", result)
return result
@@ -1448,6 +1459,7 @@ class LazyComputationExecutor:
ready=True,
job_ids=[j.id for j in final_ready],
freshly_built=jobs_created > 0 or bool(waited_job_ids),
+ computed_at=_oldest_computed_at(final_ready),
)
_log_execution("success", result)
return result
diff --git a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
index 5aa89de05efa..e923d492017b 100644
--- a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
@@ -1954,12 +1954,14 @@ class TestComputationExecutorExecute(BaseTest):
def test_returns_immediately_when_all_ranges_ready(self):
query_info, query_hash = self._make_query_info()
+ computed_at = django_timezone.now() - timedelta(minutes=30)
ready_job = PreaggregationJob.objects.create(
team=self.team,
query_hash=query_hash,
time_range_start=datetime(2024, 1, 1, tzinfo=UTC),
time_range_end=datetime(2024, 1, 2, tzinfo=UTC),
status=PreaggregationJob.Status.READY,
+ computed_at=computed_at,
expires_at=django_timezone.now() + timedelta(days=7),
)
@@ -1974,6 +1976,8 @@ class TestComputationExecutorExecute(BaseTest):
assert result.ready is True
assert ready_job.id in result.job_ids
+ # The materialized-at time of the served window is surfaced for the "data as of X" badge.
+ assert result.computed_at == computed_at
def test_inserts_missing_ranges_and_returns_all_job_ids(self):
query_info, query_hash = self._make_query_info()
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 142b49019a2b..25af06955289 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -5236,6 +5236,8 @@ export interface MarketingAnalyticsItemApi {
export interface Response12Api {
columns?: unknown[] | null
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
hasMore?: boolean | null
@@ -5245,6 +5247,8 @@ export interface Response12Api {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset?: number | null
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -5265,12 +5269,16 @@ export interface Response12Api {
export type Response13ApiResults = { [key: string]: MarketingAnalyticsItemApi }
export interface Response13Api {
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
/** Generated HogQL query. */
hogql?: string | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -7905,6 +7913,8 @@ export const MarketingAnalyticsOrderByEnumApi = {
export interface MarketingAnalyticsTableQueryResponseApi {
columns?: unknown[] | null
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
hasMore?: boolean | null
@@ -7914,6 +7924,8 @@ export interface MarketingAnalyticsTableQueryResponseApi {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset?: number | null
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -7982,12 +7994,16 @@ export interface MarketingAnalyticsTableQueryApi {
export type MarketingAnalyticsAggregatedQueryResponseApiResults = { [key: string]: MarketingAnalyticsItemApi }
export interface MarketingAnalyticsAggregatedQueryResponseApi {
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
/** Generated HogQL query. */
hogql?: string | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
/** The resolved previous/comparison period date range, when comparing against another period */
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py
index 072d3e364bc9..6c2df04a3343 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py
@@ -32,10 +32,9 @@ from .attribution_session_dimensions import session_dimensions
from .constants import UNKNOWN_CHANNEL
from .marketing_lazy_precompute import (
BACKGROUND_WARMING_TRIGGERS,
+ PRECOMPUTE_ONLY_MAX_STALE_SECONDS,
REVALIDATION_TRIGGER,
- STALE_WHILE_REVALIDATE_SECONDS,
handle_stale_served,
- serve_stale_enabled,
)
from .session_breakdown_base import UNATTRIBUTED_SESSION_VALUES
@@ -172,11 +171,7 @@ def _resolve(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -
# event time cannot recover a row that was never built.
ensure_start = read.start - timedelta(days=SESSION_READ_REACHBACK_DAYS)
revalidating = get_query_tag_value("trigger") == REVALIDATION_TRIGGER
- grace = (
- resolve_stale_while_revalidate_seconds(STALE_WHILE_REVALIDATE_SECONDS, BACKGROUND_WARMING_TRIGGERS)
- if serve_stale_enabled(runner.team)
- else None
- )
+ grace = resolve_stale_while_revalidate_seconds(PRECOMPUTE_ONLY_MAX_STALE_SECONDS, BACKGROUND_WARMING_TRIGGERS)
# Only the dedicated revalidation task may rebuild; cold user reads keep the live fallback.
result = ensure_marketing_sessions_precomputed(
runner.team,
diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
index 2a2c2a386f79..58f6646afe5c 100644
--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
@@ -50,6 +50,7 @@ from .conversion_goal_conditions import (
add_conversion_goal_property_filters,
conversion_goal_match_expr,
)
+from .errors import MarketingPrecomputeNotReady
from .marketing_analytics_config import MarketingAnalyticsConfig
from .marketing_lazy_precompute import marketing_ensure_precomputed
from .metrics import CONVERSION_GOAL_PRECOMPUTE_FALLBACK_COUNTER
@@ -301,6 +302,9 @@ class ConversionGoalProcessor:
precompute_stale: bool = False
# Passed down by the runner, since a processor has no query of its own to read it from.
filter_test_accounts: bool = False
+ # Oldest `computed_at` across this goal's served precomputes (touchpoints + conversions) — how old the
+ # goal's data can be. The runner takes the oldest across all goals for the response's "data as of X".
+ precompute_computed_at: datetime | None = None
_UTM_LEVEL_FIELD_MAP: ClassVar[dict[MarketingAnalyticsDrillDownLevel, str]] = {
MarketingAnalyticsDrillDownLevel.MEDIUM: "medium",
@@ -530,24 +534,34 @@ class ConversionGoalProcessor:
) -> ast.SelectQuery:
"""Generate multi-step funnel query with attribution window.
- Reads the preagg table when eligible, falls back to events scan on any failure.
+ Serves precompute-only when the goal is precomputable: it reads the preagg tables, and reports
+ not-ready (rather than scanning events live) when the window has not been warmed. Only a
+ non-precomputable goal, or a rare precompute build error, reaches the live events scan.
"""
if self._should_use_precompute(date_from, date_to):
# `_should_use_precompute` returns False unless both dates are set; narrow for mypy.
assert date_from is not None and date_to is not None
try:
precomputed = self._build_attribution_from_precomputes(date_from, date_to, touchpoints)
- if precomputed is not None:
- return precomputed
except Exception:
+ # A genuine build error is a rare safety valve — fall through to the live scan below rather
+ # than fail the dashboard. A not-warmed window is NOT an error; it returns None (handled
+ # in the else) so it can surface as not-ready instead of a live scan.
CONVERSION_GOAL_PRECOMPUTE_FALLBACK_COUNTER.inc()
logger.exception(
"conversion_goal_precompute_failed",
goal_id=self.goal.conversion_goal_id,
team_id=self.team.pk,
)
+ else:
+ if precomputed is not None:
+ return precomputed
+ # Precompute-only: a precomputable goal with no warm window must not fall back to the live
+ # events scan (the expensive query this path exists to avoid). Report not-ready; the warmer
+ # materializes the window and the UI shows a "computing" state until it does.
+ raise MarketingPrecomputeNotReady(goal_id=self.goal.conversion_goal_id)
- # Live events scan. Reaching here means the precompute did not serve this goal.
+ # Live events scan — reached only for non-precomputable goals, or after a precompute build error.
with self.timings.measure("ma_goal_events_fallback"):
array_collection = self.build_array_collection_query(additional_conditions)
return self.build_attribution_pipeline(array_collection)
@@ -744,6 +758,11 @@ class ConversionGoalProcessor:
if touchpoints_result.stale or conversions_result.stale:
self.precompute_stale = True
+ # Oldest materialization across the two precomputes bounds how old this goal's data can be; the
+ # runner takes the oldest across all goals for the response's "data as of X".
+ stamps = [r.computed_at for r in (touchpoints_result, conversions_result) if r.computed_at is not None]
+ self.precompute_computed_at = min(stamps) if stamps else None
+
with self.timings.measure("ma_attribution_pipeline_precomputed"):
array_collection = self._build_array_collection_from_precomputes(
touchpoints_result.job_ids, conversions_result.job_ids, date_from, date_to, window
diff --git a/products/marketing_analytics/backend/hogql_queries/errors.py b/products/marketing_analytics/backend/hogql_queries/errors.py
new file mode 100644
index 000000000000..69889115031f
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/errors.py
@@ -0,0 +1,18 @@
+from typing import Any
+
+
+class MarketingPrecomputeNotReady(Exception):
+ """A precomputable conversion goal has no warm precompute for the requested window.
+
+ Marketing analytics serves exclusively from precompute. Rather than fall back to a live events scan —
+ the expensive query this whole path exists to avoid — the read reports not-ready, and the dashboard
+ shows a "computing" state until the warmer materializes the window.
+ """
+
+ def __init__(self, goal_id: str | None = None) -> None:
+ self.goal_id = goal_id
+ # The query whose window was missing, stamped by the runner that was building when it raised. In
+ # compare mode the previous-period runner carries a shifted date range, so warming the outer
+ # runner's query would build a window that was never the one that missed.
+ self.query: Any = None
+ super().__init__(f"Precompute not ready for conversion goal {goal_id}")
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_aggregated_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_aggregated_query_runner.py
index 1b899ec43172..9b3b6ab47729 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_aggregated_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_aggregated_query_runner.py
@@ -191,6 +191,13 @@ class MarketingAnalyticsAggregatedQueryRunner(
error=self._conversion_goal_error,
)
+ def _build_not_ready_response(self) -> MarketingAnalyticsAggregatedQueryResponse:
+ return MarketingAnalyticsAggregatedQueryResponse(
+ results={},
+ modifiers=self.modifiers,
+ precomputeNotReady=True,
+ )
+
def calculate_without_compare(self) -> ast.SelectQuery:
"""Execute the query without comparison - no pagination needed"""
query = self.to_query()
@@ -226,6 +233,9 @@ class MarketingAnalyticsAggregatedQueryRunner(
previous_period_query = previous_runner.to_query()
current_period_query = self.to_query()
+ # Both periods are on screen, so the response's freshness is the older of the two. `to_query`
+ # resets this per build, so fold the previous period in only after the current one has run.
+ self.note_precompute_computed_at(previous_runner._precompute_computed_at)
join_expr = ast.JoinExpr(
table=current_period_query,
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
index 3afe6297b0e7..b00398af4848 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
@@ -3,7 +3,7 @@ from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime
from functools import cached_property
-from typing import Generic, Optional, TypeVar
+from typing import Generic, Optional, Protocol, TypeVar, cast
import structlog
import posthoganalytics
@@ -50,6 +50,7 @@ from products.marketing_analytics.backend.hogql_queries.constants import (
)
from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import (
BACKGROUND_WARMING_TRIGGERS,
+ handle_not_ready,
handle_stale_served,
marketing_ensure_precomputed,
)
@@ -59,6 +60,7 @@ from .adapters.base import MarketingSourceAdapter, QueryContext
from .adapters.factory import MarketingSourceFactory
from .conversion_goal_processor import ConversionGoalProcessor, goal_sums_a_property
from .conversion_goals_aggregator import ConversionGoalsAggregator
+from .errors import MarketingPrecomputeNotReady
from .marketing_analytics_config import MarketingAnalyticsConfig
from .utils import build_source_normalization_expr, convert_team_conversion_goals_to_objects, test_account_conditions
@@ -79,6 +81,18 @@ logger = structlog.get_logger(__name__)
ResponseType = TypeVar("ResponseType", bound=AnalyticsQueryResponseProtocol)
+
+class PrecomputeMetadataResponse(Protocol):
+ """The precompute-serving fields the conversion-goal responses carry.
+
+ Only the table and aggregated responses declare them; retention and session-breakdown responses
+ don't, and pydantic rejects unknown attributes.
+ """
+
+ precomputeNotReady: Optional[bool]
+ dataComputedAt: Optional[str]
+
+
# Discriminator column tagging each row in the compare UNION ALL with its period.
COMPARE_PERIOD_FIELD = "_period"
COMPARE_PERIOD_CURRENT = "current"
@@ -93,7 +107,7 @@ COSTS_PRECOMPUTE_TTL_SECONDS = {"0d": 6 * 60 * 60, "1d": 24 * 60 * 60, "default"
# Cap for a cost window that materialized zero rows. Short enough that a source which was mid-sync
# heals the same day, long enough that a genuinely empty window isn't re-scanned on every read.
# This bounds recomputation, not what a reader sees: the read path serves stale within
-# STALE_WHILE_REVALIDATE_SECONDS, so a $0 window can still be handed back for up to the sum of both.
+# PRECOMPUTE_ONLY_MAX_STALE_SECONDS, so a $0 window can still be handed back for up to the sum of both.
COSTS_EMPTY_RESULT_TTL_SECONDS = 6 * 60 * 60 # 6 hours
# How far back the cap above applies, measured from the window's end. A warehouse sync that is going
@@ -183,13 +197,30 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
# Set when any read-path ensure (costs, touchpoints, conversions) was served from
# expired-within-grace rows rather than rebuilt inline. Reset on each to_query.
self._precompute_stale: bool = False
+ # Oldest precompute `computed_at` across the read's conversion goals, collected while building the
+ # query. Surfaced on the response as "data as of X". None when nothing precomputed was read.
+ self._precompute_computed_at: Optional[datetime] = None
def calculate(self) -> ResponseType:
start = time.perf_counter()
try:
- response = self._calculate()
+ try:
+ response = self._calculate()
+ except MarketingPrecomputeNotReady as not_ready:
+ # A precomputable goal has no warm window: serve an explicit not-ready response rather than
+ # scan events live. Enqueue a one-off background warm so a cold team outside the rolling warm
+ # set is served on its next visit; the UI shows a "computing" state meanwhile.
+ handle_not_ready(team=self.team, query=not_ready.query or self.query)
+ self._capture_query_event("marketing analytics query not ready", start, error=not_ready)
+ return self._build_not_ready_response()
if self.limit_context == LimitContext.EXPORT:
strip_infinity_sentinels(response)
+ if "precomputeNotReady" in getattr(type(response), "model_fields", {}):
+ precompute_metadata = cast(PrecomputeMetadataResponse, response)
+ precompute_metadata.precomputeNotReady = False
+ precompute_metadata.dataComputedAt = (
+ self._precompute_computed_at.isoformat() if self._precompute_computed_at else None
+ )
self._capture_query_event("marketing analytics query performed", start)
return response
except Exception as e:
@@ -415,6 +446,8 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
)
s3_fallback_adapters.append(adapter)
continue
+ # This source's cost rows are on screen, so their age bounds the response's freshness too.
+ self.note_precompute_computed_at(result.computed_at)
# The ensure_precomputed call above materialized this source. We read by source, not by
# result.job_ids, because the `marketing_costs_precomputed` view already collapses each cell to its latest job.
materialized_source_ids.append(adapter.get_source_id())
@@ -1107,6 +1140,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
self.timings.timings.update(processor.timings.timings)
if processor.precompute_stale:
self._precompute_stale = True
+ self.note_precompute_computed_at(processor.precompute_computed_at)
if unified_cte:
ctes[UNIFIED_CONVERSION_GOALS_CTE_ALIAS] = unified_cte
@@ -1167,12 +1201,36 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
if level is not None:
self.config.drill_down_level = level
+ def note_precompute_computed_at(self, computed_at: Optional[datetime]) -> None:
+ """Fold one served precompute's `computed_at` into the read's freshness.
+
+ The oldest across every dataset the response displays — costs, each conversion goal, and the
+ previous period when comparing — bounds how old the numbers on screen can be. Taking anything
+ newer would understate staleness on the freshness badge.
+ """
+ if computed_at is None:
+ return
+ if self._precompute_computed_at is None or computed_at < self._precompute_computed_at:
+ self._precompute_computed_at = computed_at
+
def to_query(self) -> ast.SelectQuery:
+ try:
+ return self._build_query()
+ except MarketingPrecomputeNotReady as not_ready:
+ # Stamp the query this runner was building, so the read path warms the window that actually
+ # missed. A compare read builds the previous period through a second runner whose date range
+ # is shifted, and the first stamp wins because the raise unwinds straight out of that runner.
+ if not_ready.query is None:
+ not_ready.query = self.query
+ raise
+
+ def _build_query(self) -> ast.SelectQuery:
"""Generate the HogQL query using the new adapter architecture"""
with self.timings.measure("marketing_analytics_base_query"):
# Reset per build. Any read-path ensure served from expired-within-grace rows flips this, and
# the read schedules exactly one background revalidation once the query is built.
self._precompute_stale = False
+ self._precompute_computed_at = None
# Apply drill-down level from query to config
self._apply_drill_down_level()
@@ -1408,3 +1466,11 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
def _calculate(self) -> ResponseType:
"""Execute the query and return results"""
pass
+
+ def _build_not_ready_response(self) -> ResponseType:
+ """Empty typed response with `precomputeNotReady=True`, for when a goal's window is not warmed.
+
+ Only runners that build conversion-goal CTEs (table, aggregated) can raise
+ `MarketingPrecomputeNotReady`, so only they override this. Others never reach it.
+ """
+ raise NotImplementedError(f"{type(self).__name__} cannot serve a not-ready response")
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py
index cd401bcd9d2b..57f0133dfeec 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py
@@ -129,6 +129,14 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
error=self._conversion_goal_error,
)
+ def _build_not_ready_response(self) -> MarketingAnalyticsTableQueryResponse:
+ return MarketingAnalyticsTableQueryResponse(
+ results=[],
+ columns=[],
+ modifiers=self.modifiers,
+ precomputeNotReady=True,
+ )
+
def _get_column_names_for_order_by(self, select_columns: list[ast.Expr]) -> list[str]:
"""Extract column names from AST expressions for order by"""
return [col.alias if isinstance(col, ast.Alias) else str(col) for col in select_columns]
@@ -225,6 +233,9 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
previous_period_query = previous_runner.to_query()
current_period_query = self.to_query()
+ # Both periods are on screen, so the response's freshness is the older of the two. `to_query`
+ # resets this per build, so fold the previous period in only after the current one has run.
+ self.note_precompute_computed_at(previous_runner._precompute_computed_at)
# Get column names for the compare query
select_columns = self._get_filtered_select_columns(current_period_query)
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_lazy_precompute.py b/products/marketing_analytics/backend/hogql_queries/marketing_lazy_precompute.py
index de2a5d47eb7c..8d9fc658b4ea 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_lazy_precompute.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_lazy_precompute.py
@@ -30,22 +30,17 @@ from prometheus_client import Counter
from posthog import redis
from posthog.clickhouse.query_tagging import tag_queries
from posthog.models import Team
-from posthog.ph_client import feature_enabled_or_false
+from posthog.token_bucket import BucketDecision, Budget, consume
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ EXPIRY_BUFFER_SECONDS,
LazyComputationResult,
ensure_precomputed,
)
-from products.analytics_platform.backend.lazy_computation.stale_policy import resolve_stale_while_revalidate_seconds
+from products.analytics_platform.backend.lazy_computation.stale_policy import is_background_warming_request
logger = structlog.get_logger(__name__)
-# Gates the whole mechanism, so it can be rolled out gradually and killed without a deploy. Off means a
-# read materializes inline exactly as it did before this existed — and with no grace the executor never
-# reports `stale`, so no revalidation is enqueued either. Fail-safe: `feature_enabled_or_false` returns
-# False if flag evaluation breaks, which degrades to that same pre-existing behaviour.
-SERVE_STALE_FLAG = "marketing-analytics-serve-stale"
-
# The trigger the revalidation task runs under. Lives next to the trigger set so the two cannot drift.
REVALIDATION_TRIGGER = "marketingAnalyticsStaleRevalidation"
@@ -54,12 +49,6 @@ REVALIDATION_TRIGGER = "marketingAnalyticsStaleRevalidation"
# otherwise serve itself stale and never recompute.
BACKGROUND_WARMING_TRIGGERS = frozenset({REVALIDATION_TRIGGER})
-# How far past expiry a user-facing read may still be served from existing rows. Refresh normally lands
-# within minutes via the revalidation task (plus the hourly warmer for allowlisted teams); this grace is
-# the ceiling for when both of those fail. Must stay well under the framework's 48h ClickHouse expiry
-# buffer, so the underlying rows are guaranteed to still exist.
-STALE_WHILE_REVALIDATE_SECONDS = 6 * 60 * 60
-
# One revalidation per (team, query shape) per window. A dashboard renders several tiles off the same
# query shape and they all go stale together; without this they would each enqueue a rebuild of the same
# windows.
@@ -71,6 +60,11 @@ REVALIDATION_DEBOUNCE_SECONDS = 10 * 60
# rather than staying suppressed for 10 minutes with no rebuild in flight.
ENQUEUE_FAILURE_BACKOFF_SECONDS = 30
+# The debounce key is the user-controlled query shape, so distinct date ranges or draft goals each get
+# their own slot. This per-team budget caps the total background warms a team can queue, so a flood of
+# cold shapes cannot fill the shared analytics queue with long ClickHouse rebuilds.
+TEAM_WARM_BUDGET = Budget(burst=10, per_hour=30)
+
# Fields that shape only the final read, never what gets materialized, so they must not split the debounce
# key — paging or re-sorting a stale table would otherwise enqueue a rebuild per interaction. Kept
# deliberately narrow: excluding a field that *does* select precomputes (`select` gates which conversion
@@ -92,44 +86,41 @@ MARKETING_PRECOMPUTE_REVALIDATION_ENQUEUE_FAILED = Counter(
"Revalidation enqueues that failed (e.g. broker unavailable); the stale read is still served.",
)
+MARKETING_PRECOMPUTE_REVALIDATION_THROTTLED = Counter(
+ "marketing_analytics_precompute_revalidation_throttled_total",
+ "Background warms skipped because the team used up its warm budget.",
+)
-def serve_stale_enabled(team: Team) -> bool:
- """Whether this team may be served stale precomputes, cached on the team instance.
+MARKETING_PRECOMPUTE_NOT_READY_WARMED = Counter(
+ "marketing_analytics_precompute_not_ready_warmed_total",
+ "Background warms enqueued because a read found no precompute for its window (cold team on-demand).",
+)
- A single dashboard load calls the ensures several times (touchpoints, per-goal conversions, costs,
- plus a previous-period runner when comparing), so caching here keeps it to one evaluation per load
- without leaking across requests — a fresh team is loaded per request. Mirrors the caching the
- precompute flags already do in `MarketingAnalyticsConfig`.
- Test authors: the cache lives on `team._ma_serve_stale_flag`; clear it if you reuse a team across
- cases with different flag mocks.
- """
- cached = getattr(team, "_ma_serve_stale_flag", None)
- if cached is not None:
- return cached
- enabled = feature_enabled_or_false(
- SERVE_STALE_FLAG,
- str(team.uuid),
- groups={"organization": str(team.organization.id)},
- group_properties={"organization": {"id": str(team.organization.id)}},
- )
- team._ma_serve_stale_flag = enabled # type: ignore[attr-defined]
- return enabled
+# Precompute-only reads serve stale rows up to just under the framework's 48h ClickHouse-row lifetime
+# ceiling (EXPIRY_BUFFER_SECONDS). Past that the rows may be GC'd, so a read reports not-ready instead of
+# risking a job_id that no longer has data behind it. Normal freshness is far tighter (hourly warmer +
+# short TTL); this is only the ceiling for when warming falls badly behind.
+PRECOMPUTE_ONLY_MAX_STALE_SECONDS = EXPIRY_BUFFER_SECONDS - 60 * 60 # 47h, safely below the 48h buffer
def marketing_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResult:
- """`ensure_precomputed` for the marketing read path, with the product's serve-stale policy applied.
+ """`ensure_precomputed` for the marketing read path: precompute-only serving.
+
+ User-facing reads never materialize inline. They serve whatever the warmer produced — fresh, or stale
+ up to `PRECOMPUTE_ONLY_MAX_STALE_SECONDS` — and report not-ready (`ready=False`) when a window was
+ never warmed. The warmer is the sole producer, so the request thread is never blocked on a synchronous
+ INSERT. Every read-path ensure (touchpoints, conversions, costs) goes through here — one left on the
+ raw call would reintroduce inline materialization, which is the whole problem.
- User-facing calls get the grace; refreshers get none, and so does everyone when the flag is off. Every
- read-path ensure (touchpoints, conversions, costs) must go through here — one left on the raw call
- still blocks the request thread on a stale window, which is the whole problem.
+ Background refreshers (the revalidation task) are the exception: they *are* the mechanism that keeps
+ the precompute fresh, so they must run inserts and take no grace. `is_background_warming_request`
+ classifies them by the CACHE_WARMUP tag / revalidation trigger, exactly as the old grace policy did.
"""
- if "stale_while_revalidate_seconds" not in kwargs:
- kwargs["stale_while_revalidate_seconds"] = (
- resolve_stale_while_revalidate_seconds(STALE_WHILE_REVALIDATE_SECONDS, BACKGROUND_WARMING_TRIGGERS)
- if serve_stale_enabled(team)
- else None
- )
+ if is_background_warming_request(BACKGROUND_WARMING_TRIGGERS):
+ return ensure_precomputed(team=team, **kwargs)
+ kwargs.setdefault("run_inserts", False)
+ kwargs.setdefault("stale_while_revalidate_seconds", PRECOMPUTE_ONLY_MAX_STALE_SECONDS)
return ensure_precomputed(team=team, **kwargs)
@@ -178,6 +169,13 @@ def enqueue_stale_revalidation(*, team: Team, query: Any) -> None:
claimed = bool(redis.get_client().set(debounce_key, "1", ex=REVALIDATION_DEBOUNCE_SECONDS, nx=True))
if not claimed:
return
+ budget = consume(f"ma_swr_reval_rate:{team.id}", TEAM_WARM_BUDGET)
+ if isinstance(budget, BucketDecision) and not budget.allowed:
+ # Hold the slot only for a backoff, so this shape can retry once the budget refills.
+ redis.get_client().set(debounce_key, "1", ex=ENQUEUE_FAILURE_BACKOFF_SECONDS)
+ MARKETING_PRECOMPUTE_REVALIDATION_THROTTLED.inc()
+ logger.info("marketing_precompute.swr_revalidation_throttled", team_id=team.id)
+ return
revalidate_marketing_analytics_precompute.delay(
team_id=team.id, query=query.model_dump(mode="json", exclude_none=True)
)
@@ -204,3 +202,13 @@ def handle_stale_served(*, team: Team, query: Any) -> None:
MARKETING_PRECOMPUTE_STALE_SERVED.inc()
tag_queries(precompute_stale=True)
enqueue_stale_revalidation(team=team, query=query)
+
+
+def handle_not_ready(*, team: Team, query: Any) -> None:
+ """A read found no warm precompute for its window — a cold team outside the rolling warm set.
+
+ Enqueue a one-off background warm (debounced, same as revalidation) so the team's next visit is
+ served. The user sees the "computing" state until the warm lands.
+ """
+ MARKETING_PRECOMPUTE_NOT_READY_WARMED.inc()
+ enqueue_stale_revalidation(team=team, query=query)
diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_precompute_parity.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_precompute_parity.py
index 1d07bf515f19..9295e6f4f70b 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_precompute_parity.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_precompute_parity.py
@@ -550,13 +550,8 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
PreaggregationJob.objects.filter(team=self.team, id__in=original.job_ids).update(
expires_at=timezone.now() - timedelta(hours=1)
)
- with patch.object(attribution_sessions_read, "serve_stale_enabled", return_value=False):
- live, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True)
- assert not used
- with (
- patch.object(attribution_sessions_read, "serve_stale_enabled", return_value=True),
- patch.object(attribution_sessions_read, "handle_stale_served") as enqueue,
- ):
+ live, _ = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=False)
+ with patch.object(attribution_sessions_read, "handle_stale_served") as enqueue:
stale, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True)
assert used
assert stale == live
@@ -575,10 +570,11 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
assert runner._sessions_precompute_used
assert set(runner._sessions_precompute_jobs or []).isdisjoint(map(str, original.job_ids))
enqueue.assert_called_once()
- with patch.object(attribution_sessions_read, "serve_stale_enabled", return_value=False):
+ with patch.object(attribution_sessions_read, "handle_stale_served") as enqueue_after_rebuild:
fresh, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True)
assert used
assert fresh == live
+ enqueue_after_rebuild.assert_not_called()
@parameterized.expand(
[
diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py
index 2a6f3019d620..25f3f46da7b3 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py
@@ -35,8 +35,8 @@ from products.marketing_analytics.backend.hogql_queries.attribution_table_query_
MarketingAnalyticsAttributionQueryRunner,
)
from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import (
+ PRECOMPUTE_ONLY_MAX_STALE_SECONDS,
REVALIDATION_TRIGGER,
- STALE_WHILE_REVALIDATE_SECONDS,
)
@@ -50,7 +50,6 @@ class TestAttributionSessionsRead(SimpleTestCase):
return_value=HogQLContext(team_id=1),
)
)
- self.enterContext(patch.object(attribution_sessions_read, "serve_stale_enabled", return_value=False))
self.team = Team(id=1, organization=Organization(id=UUID(int=1)))
self.team.modifiers = {"personsOnEventsMode": "person_id_override_properties_on_events"}
config = TeamMarketingAnalyticsConfig(team=self.team)
@@ -129,15 +128,12 @@ class TestAttributionSessionsRead(SimpleTestCase):
@parameterized.expand(
[
- ("stale_user", True, False, True, True),
- ("flag_off", False, False, False, False),
- ("revalidation", True, True, False, True),
- ("cold_user", True, False, False, False),
+ ("stale_user", False, True, True),
+ ("revalidation", True, False, True),
+ ("cold_user", False, False, False),
]
)
- def test_stale_policy_and_revalidation(
- self, _name: str, flag: bool, refreshing: bool, stale: bool, ready: bool
- ) -> None:
+ def test_stale_policy_and_revalidation(self, _name: str, refreshing: bool, stale: bool, ready: bool) -> None:
runner = MarketingAnalyticsAttributionQueryRunner(
team=self.team,
modifiers=HogQLQueryModifiers(personsOnEventsMode="person_id_override_properties_on_events"),
@@ -153,7 +149,6 @@ class TestAttributionSessionsRead(SimpleTestCase):
patch.object(
marketing_sessions_precompute, "create_default_modifiers_for_team", return_value=runner.modifiers
),
- patch.object(attribution_sessions_read, "serve_stale_enabled", return_value=flag),
patch.object(attribution_sessions_read, "handle_stale_served") as revalidate,
patch.object(
marketing_sessions_precompute,
@@ -167,7 +162,7 @@ class TestAttributionSessionsRead(SimpleTestCase):
ensure.assert_called_once()
assert ensure.call_args.kwargs["run_inserts"] is refreshing
assert ensure.call_args.kwargs["stale_while_revalidate_seconds"] == (
- STALE_WHILE_REVALIDATE_SECONDS if flag and not refreshing else None
+ None if refreshing else PRECOMPUTE_ONLY_MAX_STALE_SECONDS
)
assert revalidate.call_count == int(stale)
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_dedup.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_dedup.py
index 5b7d980cc7e5..4a322ea161e8 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_dedup.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_dedup.py
@@ -2,6 +2,7 @@ import uuid
from datetime import UTC, datetime
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
+from unittest.mock import patch
from django.test import override_settings
@@ -55,8 +56,16 @@ class TestConversionGoalPrecomputeDedup(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
self._clean()
+ # Reads are precompute-only (they never build inline). These tests warm and read in-process with
+ # no separate warmer, so treat the in-test ensures as a producer to materialize the windows first.
+ self._warmer_patcher = patch(
+ "products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute.is_background_warming_request",
+ return_value=True,
+ )
+ self._warmer_patcher.start()
def tearDown(self):
+ self._warmer_patcher.stop()
self._clean()
super().tearDown()
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py
index bd1d03765a8d..60812ccfb0d2 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py
@@ -1,6 +1,7 @@
from datetime import UTC, datetime
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
+from unittest.mock import patch
from django.test import override_settings
@@ -25,8 +26,17 @@ class TestConversionGoalPrecomputeEquivalence(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
self._clean_preaggregation_data()
+ # Reads are precompute-only (they never build inline), but these tests warm and read in-process
+ # with no separate warmer. Treat the in-test ensures as a producer so the precompute path
+ # materializes its windows before reading — the read shape is identical to a warm read's.
+ self._warmer_patcher = patch(
+ "products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute.is_background_warming_request",
+ return_value=True,
+ )
+ self._warmer_patcher.start()
def tearDown(self):
+ self._warmer_patcher.stop()
self._clean_preaggregation_data()
super().tearDown()
@@ -320,7 +330,8 @@ class TestConversionGoalPrecomputeEquivalence(ClickhouseTestMixin, APIBaseTest):
processor = self._make_processor(precompute=True)
# Materialize a job spanning December — a wider prior request the lazy framework reuses for the
- # narrow one below (find_existing_jobs matches the overlapping wider job).
+ # narrow one below (find_existing_jobs matches the overlapping wider job). The class-level producer
+ # patch lets this ensure build (reads are precompute-only and never build inline).
processor.generate_cte_query(
additional_conditions=[],
date_from=datetime(2024, 12, 1, tzinfo=UTC),
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py
index 341c5e68ed2a..826131dd0e7a 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py
@@ -80,6 +80,14 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):
_deterministic_job_uuid_factory(),
)
self._job_uuid_patcher.start()
+ # Reads are precompute-only (they never build inline), but these tests assert the precompute-read
+ # CTE and have no separate warmer. Treat the in-test ensures as a producer so they materialize the
+ # windows first — the resulting CTE is byte-identical to a warm read's. Mirrors the Dagster warmer.
+ self._warmer_patcher = patch(
+ "products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute.is_background_warming_request",
+ return_value=True,
+ )
+ self._warmer_patcher.start()
self.config = MarketingAnalyticsConfig.from_team(self.team)
self.config.conversion_goal_precomputation_enabled = True
self.date_range = QueryDateRange(
@@ -90,6 +98,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):
)
def tearDown(self):
+ self._warmer_patcher.stop()
self._job_uuid_patcher.stop()
super().tearDown()
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py
index 5eb3b2f3cf33..42860330e250 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py
@@ -114,6 +114,52 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
schema_map={"utm_campaign_name": "utm_campaign", "utm_source_name": "utm_source"},
)
+ def test_precompute_only_read_surfaces_not_ready_when_unwarmed(self):
+ # The core of precompute-only serving: a precomputable goal whose window the warmer has not built
+ # must return an explicit not-ready response — never silently fall back to the live events scan
+ # (the expensive query this path exists to avoid) and never silently show zeros.
+ query = MarketingAnalyticsTableQuery(
+ dateRange=self.default_date_range,
+ limit=DEFAULT_LIMIT,
+ offset=0,
+ properties=[],
+ draftConversionGoal=self._create_test_conversion_goal("warm_me"),
+ )
+ runner = self._create_query_runner(query)
+ # Precompute on, nothing warmed — the read must report not-ready rather than scan events.
+ runner.config.conversion_goal_precomputation_enabled = True
+
+ response = runner.calculate()
+
+ assert response.precomputeNotReady is True
+ assert response.results == []
+ assert response.dataComputedAt is None
+
+ @patch(f"{_BASE_RUNNER}.handle_not_ready")
+ def test_compare_read_warms_the_period_that_missed(self, handle_not_ready):
+ # A compare read builds the previous period through a second runner with a shifted date range, and
+ # that runner is the one that goes not-ready first. Warming the requested window instead would
+ # leave the previous period cold, so every retry reports not-ready again.
+ query = MarketingAnalyticsTableQuery(
+ dateRange=self.default_date_range,
+ limit=DEFAULT_LIMIT,
+ offset=0,
+ properties=[],
+ compareFilter=CompareFilter(compare=True),
+ draftConversionGoal=self._create_test_conversion_goal("warm_me"),
+ )
+ # Set on the team, not the runner: the previous-period runner builds its own config from the same
+ # team instance, and it is the one that has to read the flag as on.
+ self.team._ma_precompute_flags = {"conversion": True, "costs": False, "sessions": False} # type: ignore[attr-defined]
+ runner = self._create_query_runner(query)
+
+ response = runner.calculate()
+
+ assert response.precomputeNotReady is True
+ warmed = handle_not_ready.call_args.kwargs["query"]
+ assert warmed.dateRange.date_from < self.default_date_range.date_from
+ assert warmed.dateRange.date_to < self.default_date_range.date_to
+
def test_initialization_basic(self):
runner = self._create_query_runner()
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_lazy_precompute.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_lazy_precompute.py
index 3204886fc040..6d6dbbd52d2d 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_lazy_precompute.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_lazy_precompute.py
@@ -11,9 +11,11 @@ from posthog.clickhouse.query_tagging import Feature, get_query_tag_value, reset
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import (
ENQUEUE_FAILURE_BACKOFF_SECONDS,
+ PRECOMPUTE_ONLY_MAX_STALE_SECONDS,
REVALIDATION_TRIGGER,
- STALE_WHILE_REVALIDATE_SECONDS,
+ TEAM_WARM_BUDGET,
_query_shape_key,
+ handle_not_ready,
handle_stale_served,
marketing_ensure_precomputed,
)
@@ -30,10 +32,8 @@ class TestMarketingLazyPrecompute(BaseTest):
super().setUp()
self.query = MarketingAnalyticsTableQuery(dateRange=DateRange(date_from="-7d"), properties=[])
redis.get_client().delete(f"ma_swr_reval:{self.team.id}:{_query_shape_key(self.query)}")
+ redis.get_client().delete(f"ma_swr_reval_rate:{self.team.id}")
reset_query_tags()
- # Flag on by default here; the flag's own behaviour is covered by test_flag_gates_serve_stale.
- # Cached on the team instance, so it must be cleared between cases that mock it differently.
- self.team._ma_serve_stale_flag = True # type: ignore[attr-defined]
def tearDown(self):
reset_query_tags()
@@ -41,18 +41,20 @@ class TestMarketingLazyPrecompute(BaseTest):
@parameterized.expand(
[
- ("user_facing", None),
- # The Dagster warmer, which tags CACHE_WARMUP. Served its own stale rows it would persist
- # them as fresh and never rebuild, and marketing data would stop refreshing entirely.
- ("dagster_warmer", {"feature": Feature.CACHE_WARMUP}),
- ("revalidation_task", {"trigger": REVALIDATION_TRIGGER, "feature": Feature.CACHE_WARMUP}),
+ # User-facing read: precompute-only. Never build inline (run_inserts=False), and serve stale
+ # up to the ceiling so a warmer that has fallen behind still answers instead of going not-ready.
+ ("user_facing", None, False),
+ # The Dagster warmer, which tags CACHE_WARMUP. It is the producer, so it must build (default
+ # run_inserts=True) and take no grace — served its own stale rows it would never recompute.
+ ("dagster_warmer", {"feature": Feature.CACHE_WARMUP}, True),
+ ("revalidation_task", {"trigger": REVALIDATION_TRIGGER, "feature": Feature.CACHE_WARMUP}, True),
# Belt: should the feature tag ever be clobbered before the ensure (web hit exactly this),
# the trigger alone must still classify the revalidation task as a refresher.
- ("revalidation_task_feature_clobbered", {"trigger": REVALIDATION_TRIGGER, "feature": Feature.QUERY}),
+ ("revalidation_task_feature_clobbered", {"trigger": REVALIDATION_TRIGGER, "feature": Feature.QUERY}, True),
]
)
@mock.patch(f"{_MODULE}.ensure_precomputed")
- def test_serve_stale_grace_by_caller(self, _name, tags, mock_ensure):
+ def test_read_serves_precompute_only_refresher_builds(self, _name, tags, is_refresher, mock_ensure):
mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[])
if tags is None:
marketing_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)
@@ -60,39 +62,23 @@ class TestMarketingLazyPrecompute(BaseTest):
with tags_context(**tags):
marketing_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)
- grace = mock_ensure.call_args.kwargs["stale_while_revalidate_seconds"]
- if tags is None:
- assert grace == STALE_WHILE_REVALIDATE_SECONDS
+ kwargs = mock_ensure.call_args.kwargs
+ if is_refresher:
+ # A refresher must not be forced read-only or served stale, or it would never rebuild.
+ assert "run_inserts" not in kwargs, f"refresher {tags} must be allowed to build"
+ assert "stale_while_revalidate_seconds" not in kwargs, f"refresher {tags} must not be served stale"
else:
- assert grace is None, f"refresher {tags} must not be served stale"
-
- @parameterized.expand([("flag_on", True, STALE_WHILE_REVALIDATE_SECONDS), ("flag_off", False, None)])
- @mock.patch(f"{_MODULE}.ensure_precomputed")
- @mock.patch(f"{_MODULE}.feature_enabled_or_false")
- def test_flag_gates_serve_stale(self, _name, flag, expected_grace, flag_eval, mock_ensure):
- # The kill switch. Off must hand the executor no grace at all, so the read materializes inline
- # exactly as it did before serve-stale existed (and, getting no `stale`, enqueues no revalidation).
- del self.team._ma_serve_stale_flag # type: ignore[attr-defined]
- flag_eval.return_value = flag
- mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[])
-
- marketing_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)
-
- assert mock_ensure.call_args.kwargs["stale_while_revalidate_seconds"] == expected_grace
-
- @mock.patch(f"{_MODULE}.ensure_precomputed")
- @mock.patch(f"{_MODULE}.feature_enabled_or_false")
- def test_flag_is_evaluated_once_per_team_across_the_reads_ensures(self, flag_eval, mock_ensure):
- # One load fires this several times (touchpoints, per-goal conversions, costs); each evaluation
- # would otherwise be a flag call plus a $feature_flag_called event on the read path.
- del self.team._ma_serve_stale_flag # type: ignore[attr-defined]
- flag_eval.return_value = True
- mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[])
+ assert kwargs["run_inserts"] is False, "user-facing read must never materialize inline"
+ assert kwargs["stale_while_revalidate_seconds"] == PRECOMPUTE_ONLY_MAX_STALE_SECONDS
- for _ in range(4):
- marketing_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)
+ @mock.patch(_DELAY)
+ def test_handle_not_ready_enqueues_a_background_warm(self, delay):
+ # A cold team outside the rolling warm set reads not-ready; that must trigger a one-off background
+ # warm so its next visit is served. Without this, cold teams stay not-ready forever.
+ handle_not_ready(team=self.team, query=self.query)
- assert flag_eval.call_count == 1
+ assert delay.call_count == 1
+ assert delay.call_args.kwargs["team_id"] == self.team.pk
@mock.patch(_DELAY)
def test_handle_stale_served_tags_read_and_debounces_same_shape(self, delay):
@@ -131,6 +117,22 @@ class TestMarketingLazyPrecompute(BaseTest):
assert delay.call_count == expected_enqueues
+ @mock.patch(_DELAY)
+ def test_distinct_shapes_are_capped_by_the_team_warm_budget(self, delay):
+ # Each date range gets its own debounce slot, so a flood of cold shapes must still stop at the
+ # team's budget instead of queueing one long rebuild per shape.
+ shapes = [
+ self.query.model_copy(update={"dateRange": DateRange(date_from=f"-{days}d")})
+ for days in range(1, TEAM_WARM_BUDGET.burst + 4)
+ ]
+ for shape in shapes:
+ redis.get_client().delete(f"ma_swr_reval:{self.team.id}:{_query_shape_key(shape)}")
+ handle_not_ready(team=self.team, query=shape)
+
+ assert delay.call_count == TEAM_WARM_BUDGET.burst
+ throttled_key = f"ma_swr_reval:{self.team.id}:{_query_shape_key(shapes[-1])}"
+ assert 0 < redis.get_client().ttl(throttled_key) <= ENQUEUE_FAILURE_BACKOFF_SECONDS
+
@mock.patch(_DELAY)
@mock.patch(f"{_MODULE}.redis.get_client", side_effect=Exception("redis down"))
def test_enqueue_failure_still_serves_the_stale_read(self, _redis, delay):
diff --git a/products/marketing_analytics/backend/management/commands/verify_marketing_precompute_parity.py b/products/marketing_analytics/backend/management/commands/verify_marketing_precompute_parity.py
new file mode 100644
index 000000000000..7aa7cb534d10
--- /dev/null
+++ b/products/marketing_analytics/backend/management/commands/verify_marketing_precompute_parity.py
@@ -0,0 +1,186 @@
+"""Compare the marketing-analytics precompute read path against the live path, per team, for the
+aggregated totals — the faithful "does precompute return the same numbers as live" check.
+
+This is the gate before flipping `marketing-analytics-precomputation` on for a team: run it against a
+cohort, confirm the precomputed totals match the live events-scan totals within tolerance, then enable
+the read flag knowing the served numbers won't move.
+
+Why a command and not raw ClickHouse SQL: the precompute read selects which preagg `job_id`s to merge
+(Postgres job tracking) then merges aggregate states across them. Reading the preagg tables directly
+would re-implement that job selection and risk diverging from it. Running the actual runner both ways
+exercises the real read path, so the comparison reflects what users would see.
+
+Each team is warmed inline as it's checked (the precompute read runs under the CACHE_WARMUP tag, which
+routes its ensures to the build path), so a cohort can be validated without deploying the warmer first.
+
+ python manage.py verify_marketing_precompute_parity --teams 2
+ python manage.py verify_marketing_precompute_parity --teams-file cohort.txt --date-from -8d --date-to -1d
+"""
+
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError
+
+from posthog.clickhouse.query_tagging import Feature, tags_context
+from posthog.dataclasses import frozen
+from posthog.hogql_queries.query_runner import get_query_runner
+from posthog.models import Team
+
+
+@frozen
+class _ParityReading:
+ """One team's numbers from one read path, plus how the precompute path answered.
+
+ `served_from_precompute` is only true when the read actually read the preagg tables —
+ `dataComputedAt` is set only then. If it is false the path either reported not-ready (no warm
+ window, `not_ready`) or fell back to live (non-precomputable goal or build error). Both make the
+ comparison vacuous, but they are different operator verdicts, so they stay apart."""
+
+ metrics: dict[str, float]
+ served_from_precompute: bool
+ not_ready: bool
+
+
+def _aggregated_query(*, date_from: str, date_to: str) -> dict[str, Any]:
+ return {
+ "kind": "MarketingAnalyticsAggregatedQuery",
+ "dateRange": {"date_from": date_from, "date_to": date_to},
+ "properties": [],
+ }
+
+
+def _results_to_dict(results: Any) -> dict[str, float]:
+ # The aggregated response is a {metric_name: MarketingAnalyticsItem} map; keep the numeric metrics.
+ items = results.values() if isinstance(results, dict) else results
+ out: dict[str, float] = {}
+ for item in items:
+ value = getattr(item, "value", None)
+ key = getattr(item, "key", None)
+ if key is not None and isinstance(value, int | float):
+ out[str(key)] = float(value)
+ return out
+
+
+def _pct_diff(precompute_value: float, live_value: float) -> float:
+ if live_value == 0:
+ return 0.0 if precompute_value == 0 else 100.0
+ return abs(precompute_value - live_value) / live_value * 100
+
+
+def _run(team: Team, query: dict[str, Any], *, use_precompute: bool) -> _ParityReading:
+ runner = get_query_runner(query=query, team=team)
+ # Force the path under test regardless of the team's flag: the precompute read warms inline under the
+ # CACHE_WARMUP tag (its ensures build), the live read scans events.
+ runner.config.conversion_goal_precomputation_enabled = use_precompute # type: ignore[attr-defined]
+ if use_precompute:
+ with tags_context(feature=Feature.CACHE_WARMUP):
+ response = runner.calculate()
+ else:
+ response = runner.calculate()
+ return _ParityReading(
+ metrics=_results_to_dict(response.results),
+ served_from_precompute=getattr(response, "dataComputedAt", None) is not None,
+ not_ready=bool(getattr(response, "precomputeNotReady", False)),
+ )
+
+
+class Command(BaseCommand):
+ help = "Compare marketing-analytics precompute vs live aggregated metrics per team."
+
+ def add_arguments(self, parser: Any) -> None:
+ group = parser.add_mutually_exclusive_group(required=True)
+ group.add_argument("--teams", type=str, help="Comma-separated team ids.")
+ group.add_argument("--teams-file", type=str, help="File with comma- or newline-separated team ids.")
+ parser.add_argument("--date-from", type=str, default="-8d", help="Window start (default -8d).")
+ parser.add_argument(
+ "--date-to", type=str, default="-1d", help="Window end (default -1d; excludes today's stale bucket)."
+ )
+ parser.add_argument("--tolerance", type=float, default=1.0, help="Max %% diff per metric (default 1.0).")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ team_ids = self._parse_team_ids(options)
+ date_from: str = options["date_from"]
+ date_to: str = options["date_to"]
+ tolerance: float = options["tolerance"]
+
+ teams = {t.id: t for t in Team.objects.filter(id__in=team_ids)}
+ missing = sorted(set(team_ids) - set(teams.keys()))
+ if missing:
+ self.stderr.write(f"skipping {len(missing)} unknown team ids: {missing[:20]}")
+
+ self.stdout.write(
+ f"window {date_from}..{date_to} tolerance {tolerance}% teams {len(teams)}\n"
+ f"{'team':>8} {'metric':<28} {'precompute':>14} {'live':>14} {'diff%':>7} status"
+ )
+
+ teams_pass = 0
+ teams_failed: list[int] = []
+ teams_errored: list[int] = []
+ teams_not_ready: list[int] = []
+ teams_vacuous: list[int] = []
+ query = _aggregated_query(date_from=date_from, date_to=date_to)
+
+ for team_id in team_ids:
+ team = teams.get(team_id)
+ if team is None:
+ continue
+ try:
+ precompute = _run(team, query, use_precompute=True)
+ live = _run(team, query, use_precompute=False)
+ except Exception as exc: # noqa: BLE001 — one bad team shouldn't abort the sweep
+ self.stderr.write(f"{team_id}: query failed — {type(exc).__name__}: {exc}")
+ teams_errored.append(team_id)
+ continue
+
+ # Nothing warm to read yet, so there is nothing to compare. Kept apart from the live fallback
+ # below: this one is fixed by warming the window, that one by the goal becoming precomputable.
+ if precompute.not_ready:
+ teams_not_ready.append(team_id)
+ self.stdout.write(f"{team_id:>8} NOT READY — no warm precompute window, comparison skipped")
+ continue
+
+ # The precompute run fell back to live (no precomputable goal, or a build error), so a match
+ # here compares live against live and proves nothing. Report it as vacuous, not a pass.
+ if not precompute.served_from_precompute:
+ teams_vacuous.append(team_id)
+ self.stdout.write(f"{team_id:>8} VACUOUS — precompute path fell back to live, comparison skipped")
+ continue
+
+ metric_names = sorted(set(precompute.metrics) | set(live.metrics))
+ if not metric_names:
+ teams_vacuous.append(team_id)
+ self.stdout.write(f"{team_id:>8} VACUOUS — no metrics in either read, comparison skipped")
+ continue
+
+ team_ok = True
+ for name in metric_names:
+ p = precompute.metrics.get(name, 0.0)
+ lv = live.metrics.get(name, 0.0)
+ diff = _pct_diff(p, lv)
+ ok = diff <= tolerance
+ team_ok = team_ok and ok
+ self.stdout.write(
+ f"{team_id:>8} {name:<28} {p:>14.2f} {lv:>14.2f} {diff:>7.2f} {'OK' if ok else 'OUT'}"
+ )
+ teams_pass += 1 if team_ok else 0
+ if not team_ok:
+ teams_failed.append(team_id)
+
+ self.stdout.write(
+ f"\nsummary: pass={teams_pass} out_of_tolerance={teams_failed} errored={teams_errored} "
+ f"not_ready={teams_not_ready} vacuous_fell_back_to_live={teams_vacuous}"
+ )
+
+ def _parse_team_ids(self, options: dict[str, Any]) -> list[int]:
+ raw = options.get("teams")
+ if not raw and options.get("teams_file"):
+ with open(options["teams_file"]) as f:
+ raw = f.read()
+ if not raw:
+ raise CommandError("provide --teams or --teams-file")
+ ids: list[int] = []
+ for token in raw.replace("\n", ",").split(","):
+ token = token.strip()
+ if token:
+ ids.append(int(token))
+ return ids
diff --git a/products/marketing_analytics/dags/marketing_precompute.py b/products/marketing_analytics/dags/marketing_precompute.py
index bdddbc77adcd..d420befc9ff8 100644
--- a/products/marketing_analytics/dags/marketing_precompute.py
+++ b/products/marketing_analytics/dags/marketing_precompute.py
@@ -17,23 +17,28 @@ This job moves that cost off the request path: per team it drives `ensure_precom
window so a later read is a cheap warm hit. Re-runs are cheap — already-fresh windows are skipped via
the framework's Postgres job tracking.
-Gating mirrors the read path exactly. Touchpoints + conversions are warmed only when the team's
-`marketing-analytics-precomputation` flag is on (the same flag `_should_use_precompute` checks) and the
-team has conversion goals; costs only when `marketing-analytics-costs-precomputation` is on. Warming a
-table the read won't consult would be wasted ClickHouse work, so both are evaluated from the same
-`MarketingAnalyticsConfig.from_team` the runners use. The materialization INSERT is printed userless in
-both paths, so a warmed job is byte-identical to the one a real read would create — same query hash,
-same job, no poisoning and no access-control bypass.
-
-Rollout mirrors the web dimensional precompute job: the audience is a small built-in list on PostHog
-Cloud (`DEFAULT_ROLLOUT_TEAM_IDS`), fully overridable via the `MARKETING_PRECOMPUTE_TEAM_IDS` env var
-(comma-separated team IDs; set it to empty to disable). Self-hosted defaults to no teams.
+Touchpoints + conversions are warmed for every team with a conversion goal, independent of the
+`marketing-analytics-precomputation` read flag: the precompute is populated ahead of the flag so it can
+be validated against live (see verify_marketing_precompute_parity) and the flag flip is then instant and
+safe. Costs stay gated on `marketing-analytics-costs-precomputation` — cost reads fall back to S3, so
+warming them before that flag is on is wasted work. The materialization INSERT is printed userless, so a
+warmed job is byte-identical to the one a real read would create — same query hash, same job, no
+poisoning and no access-control bypass.
+
+The audience is `MARKETING_PRECOMPUTE_TEAM_IDS`: comma-separated team IDs, empty to disable warming, or
+`auto` to warm every team that has a conversion goal AND has opened marketing analytics recently
+(query_log). Unset, it falls back to `DEFAULT_ROLLOUT_TEAM_IDS` on PostHog Cloud and to no teams
+elsewhere. `MARKETING_PRECOMPUTE_ACTIVE_DAYS` tunes the `auto` activity window.
"""
import os
from collections.abc import Callable
+from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime, timedelta
from functools import partial
+from typing import NamedTuple
+
+from django.db import connections
import dagster
import structlog
@@ -45,12 +50,13 @@ from posthog.hogql import ast
from posthog.hogql.database.database import Database
from posthog.hogql.modifiers import create_default_modifiers_for_team
-from posthog.clickhouse.client.execute import KillSwitchLevel, get_kill_switch_level
+from posthog.clickhouse.client.execute import KillSwitchLevel, get_kill_switch_level, sync_execute
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.cloud_utils import is_cloud
from posthog.dags.common import JobOwners, check_for_concurrent_runs, chunk_ranges
from posthog.models import Team
from posthog.models.team.team import DEFAULT_CURRENCY
+from posthog.models.team.team_marketing_analytics_config import TeamMarketingAnalyticsConfig
from posthog.settings import TEST
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
@@ -100,12 +106,26 @@ COST_MATERIALIZATION_GRAINS = (
MarketingAnalyticsDrillDownLevel.AD,
)
-# Built-in rollout audience used when the env var is unset: PostHog's internal dogfood project.
-# Applied on PostHog Cloud only (see get_selected_team_ids).
+# Teams warmed on PostHog Cloud when the env var is unset. Kept to the dogfood team until the fleet-wide
+# `auto` audience is validated.
DEFAULT_ROLLOUT_TEAM_IDS = [2]
-
-# Comma-separated team IDs to warm. Overrides DEFAULT_ROLLOUT_TEAM_IDS; set to empty to disable.
+# Comma-separated team IDs to warm, empty to disable warming, or `auto` to discover the audience.
SELECTED_TEAM_IDS_ENV_VAR = "MARKETING_PRECOMPUTE_TEAM_IDS"
+AUTO_AUDIENCE = "auto"
+
+# Only keep teams warm while they are actually using marketing analytics. A team that has not opened it
+# within this window drops out of the rolling warm set; its next visit reads not-ready and triggers a
+# one-off background warm. This bounds the fleet to the active population instead of every team that ever
+# set a goal. query_log retention caps the effective lookback (~14 days), which is the low end of the range
+# we want anyway.
+ACTIVE_DAYS_ENV_VAR = "MARKETING_PRECOMPUTE_ACTIVE_DAYS"
+DEFAULT_ACTIVE_DAYS = 30
+ACTIVE_TEAMS_QUERY_TIMEOUT_SECONDS = 60
+
+# Teams warmed in parallel per run. Warming is I/O-bound (ClickHouse INSERTs), so threads overlap the
+# waits; the ceiling keeps concurrent ClickHouse load and DB connections bounded. Tunable per environment.
+TEAM_CONCURRENCY_ENV_VAR = "MARKETING_PRECOMPUTE_TEAM_CONCURRENCY"
+DEFAULT_TEAM_CONCURRENCY = 8
_TOUCHPOINTS_TABLE_LABEL = LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED.value
_CONVERSIONS_TABLE_LABEL = LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED.value
@@ -128,17 +148,66 @@ MARKETING_PRECOMPUTE_TEAM_FAILED = Counter(
)
+def _recently_active_team_ids(days: int) -> set[int] | None:
+ """Teams that ran a marketing-analytics query within `days`, from query_log. None on failure.
+
+ None means "couldn't tell" (query_log unavailable / errored) and the caller skips the run. Warming
+ every goal team instead would turn one transient failure into a fleet-wide backfill.
+ """
+ try:
+ # Match on the query_type tag in log_comment (the intended API, as the web warmer does), not a
+ # substring of the SQL text — the tag is stable, the annotation format is not.
+ rows = sync_execute(
+ """
+ SELECT DISTINCT JSONExtractInt(log_comment, 'team_id') AS team_id
+ FROM clusterAllReplicas(posthog, system, query_log)
+ WHERE type != 'QueryStart'
+ AND event_time > now() - toIntervalDay(%(days)s)
+ AND JSONExtractString(log_comment, 'query_type') IN (
+ 'marketing_analytics_table_query',
+ 'marketing_analytics_aggregated_query'
+ )
+ AND team_id > 0
+ """,
+ {"days": days},
+ settings={"max_execution_time": ACTIVE_TEAMS_QUERY_TIMEOUT_SECONDS},
+ )
+ return {int(row[0]) for row in rows}
+ except Exception:
+ logger.exception("marketing_precompute_active_teams_query_failed")
+ return None
+
+
def get_selected_team_ids() -> list[int]:
- """Resolve the team allowlist.
+ """Resolve which teams to warm.
+
+ Unset, the env var falls back to DEFAULT_ROLLOUT_TEAM_IDS on PostHog Cloud only, so self-hosted never
+ warms unrelated teams that share those IDs. Set, it wins (even when empty, as a kill switch): a
+ comma-separated list with blank or invalid entries skipped.
- The env var wins if set (even to empty): a comma-separated list, blank/invalid entries skipped.
- If unset, fall back to DEFAULT_ROLLOUT_TEAM_IDS — but only on PostHog Cloud; self-hosted defaults
- to none so the job never warms unrelated teams that happen to share those IDs.
+ `auto` warms every team that both has a conversion goal (`TeamMarketingAnalyticsConfig`) and has
+ opened marketing analytics recently (query_log), which keeps the rolling warm set to the active
+ population. Cold teams are warmed on-demand on their next visit instead.
"""
raw = os.getenv(SELECTED_TEAM_IDS_ENV_VAR)
if raw is None:
return list(DEFAULT_ROLLOUT_TEAM_IDS) if is_cloud() else []
- return [int(part.strip()) for part in raw.split(",") if part.strip().isdigit()]
+ if raw.strip().lower() != AUTO_AUDIENCE:
+ return [int(part.strip()) for part in raw.split(",") if part.strip().isdigit()]
+
+ goal_team_ids = set(
+ TeamMarketingAnalyticsConfig.objects.exclude(_conversion_goals=[])
+ .exclude(_conversion_goals__isnull=True)
+ .values_list("team_id", flat=True)
+ )
+ if not goal_team_ids:
+ return []
+
+ active_days = int(os.getenv(ACTIVE_DAYS_ENV_VAR, str(DEFAULT_ACTIVE_DAYS)))
+ active_team_ids = _recently_active_team_ids(active_days)
+ if active_team_ids is None:
+ return []
+ return sorted(goal_team_ids & active_team_ids)
def _ensure_chunks(
@@ -192,16 +261,22 @@ def _ensure_chunks(
def _ensure_touchpoints_for_team(
- context: dagster.OpExecutionContext, team: Team, start: datetime, end: datetime, chunk_days: int
+ context: dagster.OpExecutionContext,
+ team: Team,
+ filter_test_accounts: bool,
+ start: datetime,
+ end: datetime,
+ chunk_days: int,
) -> int:
"""Warm the goal-agnostic touchpoints table over [start, end] (start already reaches back past the
attribution window). One warmed window serves every conversion goal / attribution mode.
Test-account filtering is the one thing that splits it: the filter is baked into the insert query,
which the framework hashes for the job key, so warming the wrong variant leaves every read to
- materialize inline. The team's own setting is what the dashboard sends, so warm that one.
+ materialize inline. The team's own setting is what the dashboard sends, so warm that one. It is read
+ by `_plan_team` on the main thread, because reading the team extension here would query Postgres from
+ a worker thread.
"""
- filter_test_accounts = team.marketing_analytics_config.filter_test_accounts
return _ensure_chunks(
context,
team,
@@ -218,15 +293,17 @@ def _ensure_conversions_for_team(
context: dagster.OpExecutionContext,
team: Team,
config: MarketingAnalyticsConfig,
+ goals: list,
+ filter_test_accounts: bool,
start: datetime,
end: datetime,
chunk_days: int,
) -> tuple[int, int]:
"""Warm the per-goal conversions table over [start, end] (no attribution backfill — the conversion
event itself must fall in-range). One lazy job per precomputable goal; ineligible goals are skipped
- with the same rule the read path uses (is_goal_precomputable). Returns (goals_warmed, failures).
+ with the same rule the read path uses (is_goal_precomputable). `goals` are converted on the main
+ thread (see _plan_team) so this does no Django ORM. Returns (goals_warmed, failures).
"""
- goals = convert_team_conversion_goals_to_objects(team.marketing_analytics_config.conversion_goals, team.pk)
goals_warmed = 0
failures = 0
for index, goal in enumerate(goals):
@@ -236,7 +313,7 @@ def _ensure_conversions_for_team(
team=team,
config=config,
user=None,
- filter_test_accounts=team.marketing_analytics_config.filter_test_accounts,
+ filter_test_accounts=filter_test_accounts,
)
if not processor.is_goal_precomputable():
continue
@@ -314,108 +391,196 @@ def _ensure_costs_for_team(
return warmed, failures
-def ensure_marketing_precompute_op(context: dagster.OpExecutionContext) -> dict[str, int]:
- """Drive ensure_precomputed for the marketing precompute tables over the rolling window per team.
+class _TeamWarmPlan(NamedTuple):
+ """What to warm for one team, decided on the main thread so worker threads do no Django ORM reads.
- Per team, gated on the same flags the read path checks: touchpoints + conversions when the
- conversion precompute flag is on and the team has goals; costs when the costs precompute flag is on
- and the team has warehouse tables. Each team's setup and each warming block is isolated: an
- unexpected error (e.g. a broken warehouse source failing Database.create_for) is logged and counted,
- never aborting the rest of the allowlist.
+ `from_team` primes the flag + `marketing_analytics_config` caches on the `team` instance, so the
+ worker's downstream accesses (e.g. reading conversion goals) are cache hits, not queries that would
+ deadlock against the test transaction — and in production keep the parallel section to ClickHouse.
+ """
- `conversion_teams` / `costs_teams` count teams whose block ran to completion without an unexpected
- error (flag on + its raw material present — goals / warehouse tables), symmetric to each other. They
- are not success counts: per-chunk outcomes live in `failures` and the MARKETING_PRECOMPUTE_CHUNK_*
- metrics (a block can complete having warmed zero chunks, e.g. all goals ineligible).
+ team: Team
+ config: MarketingAnalyticsConfig
+ conversion_goals: list
+ attribution_window_days: int
+ filter_test_accounts: bool
+ warm_costs: bool
+
+ @property
+ def warm_conversions(self) -> bool:
+ return bool(self.conversion_goals)
+
+
+class _WarmCounts(NamedTuple):
+ """Per-team warming outcome: teams whose conversion / cost block completed, and per-chunk failures."""
+
+ conversion_teams: int
+ costs_teams: int
+ failures: int
+
+
+def _plan_team(team: Team) -> _TeamWarmPlan | None:
+ """Main-thread setup: read config, flags and goals so worker threads do no Django ORM. None on failure.
+
+ Every DB read the warming does happens here — flag evaluation, the conversion goals, and the
+ cost-source check — so a worker thread never queries Postgres (which would deadlock against the test
+ transaction and, in production, serialise the parallel section behind DB round-trips).
+
+ Conversion warming is deliberately NOT gated on the `marketing-analytics-precomputation` read flag: we
+ populate the precompute for every team with a goal so it can be validated (see the parity command)
+ while reads still serve live, then flip the read flag per team knowing the data is already warm. Costs
+ stay gated on their own flag — cost reads fall back to S3, so warming them before that flag is on is
+ wasted work.
"""
- # Tag every ClickHouse query this op drives (schema introspection during Database.create_for and the
- # materialization INSERTs) so warmer-driven load is attributable in query_log, distinct from the
- # on-read materialization the query runner triggers. The read path is tagged via its runner context.
- tag_queries(product=Product.MARKETING_ANALYTICS, feature=Feature.CACHE_WARMUP)
+ try:
+ config = MarketingAnalyticsConfig.from_team(team)
+ ma_config = team.marketing_analytics_config
+ conversion_goals = (
+ convert_team_conversion_goals_to_objects(ma_config.conversion_goals, team.pk)
+ if ma_config.conversion_goals
+ else []
+ )
+ return _TeamWarmPlan(
+ team=team,
+ config=config,
+ conversion_goals=conversion_goals,
+ attribution_window_days=ma_config.attribution_window_days or DEFAULT_ATTRIBUTION_WINDOW_DAYS,
+ filter_test_accounts=bool(ma_config.filter_test_accounts),
+ warm_costs=bool(config.costs_precomputation_enabled and _team_has_cost_sources(team)),
+ )
+ except Exception:
+ MARKETING_PRECOMPUTE_TEAM_FAILED.labels(stage="setup").inc()
+ logger.exception("marketing_precompute_setup_failed", team_id=team.pk)
+ return None
- end = datetime.now(UTC)
- team_ids = list(dict.fromkeys(get_selected_team_ids())) # dedupe so a repeated id doesn't warm twice
- context.log.info(
- f"marketing_precompute_start teams={len(team_ids)} window_days={PRECOMPUTE_WINDOW_DAYS} "
- f"chunk_days={PRECOMPUTE_CHUNK_DAYS}"
- )
- if not team_ids:
- context.log.info(f"marketing_precompute_noop ({SELECTED_TEAM_IDS_ENV_VAR} is empty)")
- result = {"teams": 0, "conversion_teams": 0, "costs_teams": 0, "failures": 0}
- context.add_output_metadata(result)
- return result
- teams_by_id = {t.pk: t for t in Team.objects.filter(pk__in=team_ids)}
+def _warm_team(context: dagster.OpExecutionContext, plan: _TeamWarmPlan, end: datetime) -> _WarmCounts:
+ """Warm one planned team's precomputes over the rolling window.
- failures = 0
- processed = 0
+ Returns (conversion_teams, costs_teams, failures) increments. Runs in a worker thread of the op's
+ pool, so it: re-tags for query_log attribution (threads don't inherit the op's contextvars), reads no
+ Django ORM (the plan primed every cache on the main thread), contains every error (a raise would abort
+ sibling teams still in `pool.map`), and closes its thread-local connections on the way out.
+ """
+ # Pool threads don't inherit the op's query tags, so re-tag here — otherwise this team's warm INSERTs
+ # and schema introspection would be un-attributable in query_log.
+ tag_queries(product=Product.MARKETING_ANALYTICS, feature=Feature.CACHE_WARMUP)
+ team = plan.team
conversion_teams = 0
costs_teams = 0
- for team_id in team_ids:
- team = teams_by_id.get(team_id)
- if team is None:
- context.log.warning(f"marketing_precompute_team_missing team_id={team_id}")
- continue
- processed += 1
-
- try:
- # from_team evaluates both precompute flags once (cached on the team instance) — the same
- # evaluation the runners use, so the warmer and read path always agree on what to precompute.
- config = MarketingAnalyticsConfig.from_team(team)
- ma_config = team.marketing_analytics_config
- except Exception:
- MARKETING_PRECOMPUTE_TEAM_FAILED.labels(stage="setup").inc()
- context.log.exception(f"marketing_precompute_setup_failed team={team_id}")
- failures += 1
- continue
-
+ failures = 0
+ try:
# Conversions and costs are independent products behind independent flags — isolate each so a
# failure in one (e.g. Database.create_for on a broken warehouse source) still lets the other run.
- if config.conversion_goal_precomputation_enabled and ma_config.conversion_goals:
+ if plan.warm_conversions:
try:
- attribution_window_days = ma_config.attribution_window_days or DEFAULT_ATTRIBUTION_WINDOW_DAYS
# Reach back far enough that a read with up to PRECOMPUTE_WINDOW_DAYS of lookback is fully
# covered including its touchpoints attribution backfill ([date_from - attribution_window, date_to]).
- tp_start = end - timedelta(days=PRECOMPUTE_WINDOW_DAYS + attribution_window_days)
- failures += _ensure_touchpoints_for_team(context, team, tp_start, end, PRECOMPUTE_CHUNK_DAYS)
+ tp_start = end - timedelta(days=PRECOMPUTE_WINDOW_DAYS + plan.attribution_window_days)
+ failures += _ensure_touchpoints_for_team(
+ context, team, plan.filter_test_accounts, tp_start, end, PRECOMPUTE_CHUNK_DAYS
+ )
# Conversions need no attribution backfill — the conversion event must fall in the query range.
# Goals that aren't precomputable (non-Events/Actions, schema remaps, person/cohort filters) are
# skipped inside; a team can warm touchpoints but no conversions if no goal qualifies.
conv_start = end - timedelta(days=PRECOMPUTE_WINDOW_DAYS)
_goals_warmed, conv_failures = _ensure_conversions_for_team(
- context, team, config, conv_start, end, PRECOMPUTE_CHUNK_DAYS
+ context,
+ team,
+ plan.config,
+ plan.conversion_goals,
+ plan.filter_test_accounts,
+ conv_start,
+ end,
+ PRECOMPUTE_CHUNK_DAYS,
)
failures += conv_failures
conversion_teams += 1
except Exception:
MARKETING_PRECOMPUTE_TEAM_FAILED.labels(stage="conversions").inc()
- context.log.exception(f"marketing_precompute_conversions_failed team={team_id}")
+ logger.exception("marketing_precompute_conversions_failed", team_id=team.pk)
failures += 1
- # Symmetric with the conversions gate: costs' prerequisite "raw material" is warehouse tables
- # (every cost adapter needs one) the way conversions' is goals. Gating here also skips the
- # ~550ms Database.create_for for teams that can't have any cost source.
- if config.costs_precomputation_enabled:
+ if plan.warm_costs:
try:
- if _team_has_cost_sources(team):
- costs_start = end - timedelta(days=PRECOMPUTE_WINDOW_DAYS)
- _sources_warmed, costs_failures = _ensure_costs_for_team(
- context, team, costs_start, end, PRECOMPUTE_CHUNK_DAYS
- )
- failures += costs_failures
- costs_teams += 1 # after the block, mirroring conversion_teams: not counted if it raised
+ costs_start = end - timedelta(days=PRECOMPUTE_WINDOW_DAYS)
+ _sources_warmed, costs_failures = _ensure_costs_for_team(
+ context, team, costs_start, end, PRECOMPUTE_CHUNK_DAYS
+ )
+ failures += costs_failures
+ costs_teams += 1 # after the block, mirroring conversion_teams: not counted if it raised
except Exception:
MARKETING_PRECOMPUTE_TEAM_FAILED.labels(stage="costs").inc()
- context.log.exception(f"marketing_precompute_costs_failed team={team_id}")
+ logger.exception("marketing_precompute_costs_failed", team_id=team.pk)
failures += 1
+ finally:
+ connections.close_all()
+ return _WarmCounts(conversion_teams, costs_teams, failures)
+
+
+def ensure_marketing_precompute_op(context: dagster.OpExecutionContext) -> dict[str, int]:
+ """Drive ensure_precomputed for the marketing precompute tables over the rolling window per team.
+
+ Teams are warmed in parallel (`_warm_team` in a thread pool, `MARKETING_PRECOMPUTE_TEAM_CONCURRENCY`
+ workers), since warming is I/O-bound on ClickHouse and the active fleet is hundreds of teams. Each
+ team warms touchpoints + conversions when it has conversion goals, deliberately independent of the
+ `marketing-analytics-precomputation` read flag so the tables are populated before the flip; costs
+ stay gated on the costs precompute flag plus the team having warehouse tables. Every team, and each
+ warming block within it, is isolated — one failure never aborts the rest.
+
+ `conversion_teams` / `costs_teams` count teams whose block ran to completion without an unexpected
+ error (its raw material present — goals / warehouse tables), symmetric to each other. They
+ are not success counts: per-chunk outcomes live in `failures` and the MARKETING_PRECOMPUTE_CHUNK_*
+ metrics (a block can complete having warmed zero chunks, e.g. all goals ineligible).
+ """
+ # Tag the op thread too (workers re-tag themselves). Keeps any op-thread ClickHouse work attributable.
+ tag_queries(product=Product.MARKETING_ANALYTICS, feature=Feature.CACHE_WARMUP)
+
+ end = datetime.now(UTC)
+ team_ids = list(dict.fromkeys(get_selected_team_ids())) # dedupe so a repeated id doesn't warm twice
+ context.log.info(
+ f"marketing_precompute_start teams={len(team_ids)} window_days={PRECOMPUTE_WINDOW_DAYS} "
+ f"chunk_days={PRECOMPUTE_CHUNK_DAYS}"
+ )
+ if not team_ids:
+ context.log.info(f"marketing_precompute_noop ({SELECTED_TEAM_IDS_ENV_VAR} is empty)")
+ result = {"teams": 0, "conversion_teams": 0, "costs_teams": 0, "failures": 0}
+ context.add_output_metadata(result)
+ return result
+
+ teams_by_id = {t.pk: t for t in Team.objects.filter(pk__in=team_ids)}
+ teams = [teams_by_id[team_id] for team_id in team_ids if team_id in teams_by_id]
+ if len(teams) != len(team_ids):
+ context.log.warning(f"marketing_precompute_teams_missing count={len(team_ids) - len(teams)}")
+
+ # Plan on the main thread: evaluate flags + prerequisites and prime each team's caches, so the worker
+ # threads do only ClickHouse warming (no Django ORM). Setup failures are counted here.
+ failures = 0
+ plans: list[_TeamWarmPlan] = []
+ for team in teams:
+ plan = _plan_team(team)
+ if plan is None:
+ failures += 1
+ else:
+ plans.append(plan)
+
+ concurrency = int(os.getenv(TEAM_CONCURRENCY_ENV_VAR, str(DEFAULT_TEAM_CONCURRENCY)))
+ conversion_teams = 0
+ costs_teams = 0
+ if plans:
+ with ThreadPoolExecutor(max_workers=max(1, min(concurrency, len(plans))), thread_name_prefix="ma_warm") as pool:
+ for conv_inc, costs_inc, fail_inc in pool.map(lambda plan: _warm_team(context, plan, end), plans):
+ conversion_teams += conv_inc
+ costs_teams += costs_inc
+ failures += fail_inc
context.log.info(
- f"marketing_precompute_complete teams={processed} conversion_teams={conversion_teams} "
+ f"marketing_precompute_complete teams={len(teams)} conversion_teams={conversion_teams} "
f"costs_teams={costs_teams} failures={failures}"
)
result = {
- "teams": processed,
+ "teams": len(teams),
"conversion_teams": conversion_teams,
"costs_teams": costs_teams,
"failures": failures,
@@ -428,9 +593,10 @@ def ensure_marketing_precompute_op(context: dagster.OpExecutionContext) -> dict[
description=(
f"Warms the marketing analytics precompute tables ({_TOUCHPOINTS_TABLE_LABEL}, "
f"{_CONVERSIONS_TABLE_LABEL}, {_COSTS_TABLE_LABEL}) over the trailing {PRECOMPUTE_WINDOW_DAYS} "
- f"days for the teams in the {SELECTED_TEAM_IDS_ENV_VAR} allowlist, gated per table on the same "
- f"precompute flags the read path checks, by driving the lazy-computation framework's "
- f"ensure_precomputed. No-op when the allowlist is empty. Re-runs only recompute expired windows."
+ f"days for the teams in the {SELECTED_TEAM_IDS_ENV_VAR} audience, warming teams in parallel and "
+ f"gating per table on the same precompute flags the read "
+ f"path checks, by driving the lazy-computation framework's ensure_precomputed. Re-runs only "
+ f"recompute expired windows."
),
tags={
"owner": JobOwners.TEAM_WEB_ANALYTICS.value,
diff --git a/products/marketing_analytics/dags/tests/test_marketing_precompute.py b/products/marketing_analytics/dags/tests/test_marketing_precompute.py
index a8ab98713dfa..f040e922a50d 100644
--- a/products/marketing_analytics/dags/tests/test_marketing_precompute.py
+++ b/products/marketing_analytics/dags/tests/test_marketing_precompute.py
@@ -21,7 +21,6 @@ from products.marketing_analytics.backend.hogql_queries.marketing_analytics_conf
from products.marketing_analytics.backend.hogql_queries.utils import convert_team_conversion_goals_to_objects
from products.marketing_analytics.dags.marketing_precompute import (
COST_MATERIALIZATION_GRAINS,
- DEFAULT_ROLLOUT_TEAM_IDS,
PRECOMPUTE_CHUNK_DAYS,
PRECOMPUTE_WINDOW_DAYS,
SELECTED_TEAM_IDS_ENV_VAR,
@@ -30,8 +29,9 @@ from products.marketing_analytics.dags.marketing_precompute import (
marketing_precompute_job,
)
-_IS_CLOUD = "products.marketing_analytics.dags.marketing_precompute.is_cloud"
_ENSURE = "products.marketing_analytics.dags.marketing_precompute.ensure_precomputed"
+_ACTIVE = "products.marketing_analytics.dags.marketing_precompute._recently_active_team_ids"
+_IS_CLOUD = "products.marketing_analytics.dags.marketing_precompute.is_cloud"
_FF = "products.marketing_analytics.backend.hogql_queries.marketing_analytics_config.feature_enabled_or_false"
_DB = "products.marketing_analytics.dags.marketing_precompute.Database"
_FACTORY = "products.marketing_analytics.dags.marketing_precompute.MarketingSourceFactory"
@@ -122,17 +122,13 @@ class TestGetSelectedTeamIds:
assert get_selected_team_ids() == expected
def test_env_set_empty_disables(self):
- with patch(_IS_CLOUD, return_value=True), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: ""}):
+ # The override wins even when empty — an explicit kill switch, regardless of configured teams.
+ with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: ""}):
assert get_selected_team_ids() == []
- @parameterized.expand(
- [
- ("cloud_uses_default_rollout", True, DEFAULT_ROLLOUT_TEAM_IDS),
- ("off_cloud_is_empty", False, []),
- ]
- )
- def test_unset_behavior_depends_on_cloud(self, _name, cloud, expected):
- with patch(_IS_CLOUD, return_value=cloud), patch.dict(os.environ, {}, clear=False):
+ @parameterized.expand([("cloud", True, [2]), ("self_hosted", False, [])])
+ def test_unset_defaults_to_rollout_teams_on_cloud_only(self, _name, cloud, expected):
+ with patch.dict(os.environ, {}, clear=False), patch(_IS_CLOUD, return_value=cloud):
os.environ.pop(SELECTED_TEAM_IDS_ENV_VAR, None)
assert get_selected_team_ids() == expected
@@ -148,17 +144,53 @@ class TestConversionWarming(APIBaseTest):
team.marketing_analytics_config.save()
return team
+ def test_auto_audience_is_recently_active_teams_with_goals(self):
+ # The rolling warm set is bounded to the active population: a team must both have a conversion goal
+ # and have opened marketing analytics recently. A team with goals but no recent activity drops out
+ # (warmed on-demand on its next visit instead); a team with no goals is never in scope.
+ active = self._make_team("active", goals=[_PRECOMPUTABLE_GOAL])
+ inactive = self._make_team("inactive", goals=[_PRECOMPUTABLE_GOAL])
+ empty_goals = self._make_team("empty_goals", goals=[])
+
+ with (
+ patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: "auto"}),
+ patch(_ACTIVE, return_value={active.pk}),
+ ):
+ selected = get_selected_team_ids()
+
+ assert active.pk in selected
+ assert inactive.pk not in selected
+ assert empty_goals.pk not in selected
+
+ def test_auto_skips_the_run_when_activity_unknown(self):
+ # Warming every goal team on a query_log failure would be a fleet-wide backfill.
+ self._make_team("with_goals", goals=[_PRECOMPUTABLE_GOAL])
+
+ with (
+ patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: "auto"}),
+ patch(_ACTIVE, return_value=None),
+ ):
+ selected = get_selected_team_ids()
+
+ assert selected == []
+
@patch(_ENSURE, new_callable=_ready_mock)
@patch(_SINGLE_CHUNK, _BIG_CHUNK)
- def test_conversion_flag_off_skips_everything(self, ensure_mock):
+ def test_conversion_warming_is_decoupled_from_the_read_flag(self, ensure_mock):
+ # Warming is deliberately NOT gated on the read flag: we populate the precompute ahead of the flag
+ # so it can be validated, then flip reads. A team with a goal warms conversions even with the read
+ # flag off. Costs stay gated on their own flag (off here), so nothing costs-related warms.
team = self._make_team("A", goals=[_PRECOMPUTABLE_GOAL])
with (
patch(_FF, _flag_fn(conversion=False, costs=False)),
patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}),
):
result = ensure_marketing_precompute_op(dagster.build_op_context())
- assert result == {"teams": 1, "conversion_teams": 0, "costs_teams": 0, "failures": 0}
- ensure_mock.assert_not_called()
+ assert result["conversion_teams"] == 1
+ assert result["costs_teams"] == 0
+ tables = _tables(ensure_mock)
+ assert LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED in tables
+ assert LazyComputationTable.MARKETING_COSTS_PREAGGREGATED not in tables
@patch(_ENSURE, new_callable=_ready_mock)
@patch(_SINGLE_CHUNK, _BIG_CHUNK)
@@ -238,6 +270,17 @@ class TestConversionWarming(APIBaseTest):
assert result == {"teams": 1, "conversion_teams": 0, "costs_teams": 0, "failures": 0}
ensure_mock.assert_not_called()
+ @patch(_ENSURE, new_callable=_ready_mock)
+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)
+ def test_pool_warms_every_team(self, ensure_mock):
+ # The parallel fan-out must process every team, not just the first — a pool that dropped teams
+ # would leave them cold. Three teams, each with a precomputable goal, must all warm.
+ teams = [self._make_team(name, goals=[_PRECOMPUTABLE_GOAL]) for name in ("A", "B", "C")]
+ ids = ",".join(str(team.pk) for team in teams)
+ with patch(_FF, _flag_fn(conversion=True)), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: ids}):
+ result = ensure_marketing_precompute_op(dagster.build_op_context())
+ assert result == {"teams": 3, "conversion_teams": 3, "costs_teams": 0, "failures": 0}
+
@patch(_ENSURE, new_callable=_ready_mock)
@patch(_SINGLE_CHUNK, _BIG_CHUNK)
def test_touchpoints_window_reaches_back_past_attribution_window(self, ensure_mock):
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 854393905d40..cfa0f598c849 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -4211,6 +4211,8 @@ export interface MarketingAnalyticsItemApi {
export interface Response12Api {
columns?: unknown[] | null
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
hasMore?: boolean | null
@@ -4220,6 +4222,8 @@ export interface Response12Api {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset?: number | null
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -4240,12 +4244,16 @@ export interface Response12Api {
export type Response13ApiResults = { [key: string]: MarketingAnalyticsItemApi }
export interface Response13Api {
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
/** Generated HogQL query. */
hogql?: string | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -6880,6 +6888,8 @@ export const MarketingAnalyticsOrderByEnumApi = {
export interface MarketingAnalyticsTableQueryResponseApi {
columns?: unknown[] | null
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
hasMore?: boolean | null
@@ -6889,6 +6899,8 @@ export interface MarketingAnalyticsTableQueryResponseApi {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset?: number | null
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -6957,12 +6969,16 @@ export interface MarketingAnalyticsTableQueryApi {
export type MarketingAnalyticsAggregatedQueryResponseApiResults = { [key: string]: MarketingAnalyticsItemApi }
export interface MarketingAnalyticsAggregatedQueryResponseApi {
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null
/** Generated HogQL query. */
hogql?: string | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
/** The resolved previous/comparison period date range, when comparing against another period */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ad1be17e698f..c8f089669d80 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7125,6 +7125,8 @@ export namespace Schemas {
export interface Response12 {
columns?: unknown[] | null;
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -7134,6 +7136,8 @@ export namespace Schemas {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset?: number | null;
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -7154,12 +7158,16 @@ export namespace Schemas {
export type Response13Results = {[key: string]: MarketingAnalyticsItem};
export interface Response13 {
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
hogql?: string | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -8427,6 +8435,8 @@ export namespace Schemas {
export interface MarketingAnalyticsTableQueryResponse {
columns?: unknown[] | null;
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -8436,6 +8446,8 @@ export namespace Schemas {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset?: number | null;
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -8499,12 +8511,16 @@ export namespace Schemas {
export type MarketingAnalyticsAggregatedQueryResponseResults = {[key: string]: MarketingAnalyticsItem};
export interface MarketingAnalyticsAggregatedQueryResponse {
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
hogql?: string | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -81788,6 +81804,8 @@ export namespace Schemas {
export interface QueryResponseAlternative33 {
columns?: unknown[] | null;
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -81797,6 +81815,8 @@ export namespace Schemas {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset?: number | null;
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -81817,12 +81837,16 @@ export namespace Schemas {
export type QueryResponseAlternative34Results = {[key: string]: MarketingAnalyticsItem};
export interface QueryResponseAlternative34 {
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
hogql?: string | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -82298,6 +82322,8 @@ export namespace Schemas {
export interface QueryResponseAlternative50 {
columns?: unknown[] | null;
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -82307,6 +82333,8 @@ export namespace Schemas {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset?: number | null;
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
/** The resolved previous/comparison period date range, when comparing against another period */
@@ -82327,12 +82355,16 @@ export namespace Schemas {
export type QueryResponseAlternative51Results = {[key: string]: MarketingAnalyticsItem};
export interface QueryResponseAlternative51 {
+ /** ISO timestamp of the oldest precompute window backing this result — surfaced as "data as of X". */
+ dataComputedAt?: string | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
hogql?: string | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
+ /** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
+ precomputeNotReady?: boolean | null;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
/** The resolved previous/comparison period date range, when comparing against another period */