Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(marketing): cache source scans and respect sync readiness (#113977)

Javier Bahamondes65bc782bf6dc
diff --git a/docs/internal/marketing-source-suggestions.md b/docs/internal/marketing-source-suggestions.md
index bb3cfce59eeb..5c647f4feefb 100644
--- a/docs/internal/marketing-source-suggestions.md
+++ b/docs/internal/marketing-source-suggestions.md
@@ -60,3 +60,9 @@ Keyword reporting continues to use `keyword_performance_report`.
Campaign trend charts accept both `campaign_overview_stats` and the legacy `campaign_stats` schema.
The current schema takes precedence when both are available.
Table resolution uses schema metadata when available and otherwise recognizes source and custom table-name prefixes.
+
+## Source scan caching and readiness
+
+The setup plan caches event scans for seven days per project. Explicit refresh requests respect a one-hour cooldown.
+Source health polling refreshes metadata without forcing every dashboard query.
+Campaign reporting waits for all required schemas to complete their first sync.
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 466d172e4ce1..7c3aab0a6c7c 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -429,6 +429,7 @@ export const FEATURE_FLAGS = {
MARKETING_ANALYTICS_RETURN_METRICS: 'marketing-analytics-return-metrics', // owner: @jabahamondes #team-web-analytics — gates the ROAS column
MARKETING_ANALYTICS_ROKT_ADS: 'marketing-analytics-rokt-ads', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_SETUP: 'marketing-analytics-setup', // owner: @jabahamondes #team-web-analytics — gates the Setup tab and its setup_plan / apply_setup_ops endpoints
+ MARKETING_ANALYTICS_SOURCE_ONBOARDING: 'marketing-analytics-source-onboarding', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_TWITTER_ADS: 'marketing-analytics-twitter-ads', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_UTM_AUDIT: 'marketing-analytics-utm-audit', // owner: @jabahamondes #team-web-analytics
MAX_AI_INSIGHT_SEARCH: 'max-ai-insight-search', // owner: #team-posthog-ai
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
index 1d8adfad6b29..a95fa39dd34d 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
@@ -526,6 +526,80 @@ describe('marketingAnalyticsLogic', () => {
expect(logic.values.unconfiguredNativeSources).toEqual([])
})
+ it.each([
+ [false, false, true, false],
+ [true, false, true, false],
+ [false, true, true, false],
+ [true, true, false, false],
+ [true, true, true, true],
+ ])(
+ 'requires both enabled marketing schemas to finish their first sync (%s, %s, %s)',
+ async (campaignSynced, statsSynced, enabled, ready) => {
+ logic = marketingAnalyticsLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ const source = {
+ id: 'meta-first-sync',
+ source_type: 'MetaAds',
+ schemas: [
+ {
+ id: 'campaigns',
+ name: 'campaigns',
+ should_sync: enabled,
+ last_synced_at: campaignSynced ? dayjs() : null,
+ },
+ {
+ id: 'campaign_stats',
+ name: 'campaign_stats',
+ should_sync: enabled,
+ last_synced_at: statsSynced ? dayjs() : null,
+ },
+ { id: 'other', name: 'other', should_sync: true, last_synced_at: dayjs() },
+ ],
+ } as ExternalDataSource
+ await expectLogic(logic, () =>
+ logic.actions.loadSourcesSuccess({ count: 1, next: null, previous: null, results: [source] })
+ ).toFinishAllListeners()
+ expect(logic.values.hasSyncedMarketingSources).toBe(ready)
+ }
+ )
+
+ it('does not reload analytics queries when polling only changes sync status', async () => {
+ const source = {
+ id: 'meta-health',
+ source_type: 'MetaAds',
+ status: ExternalDataJobStatus.Running,
+ schemas: ['campaigns', 'campaign_stats'].map((name) => ({
+ id: name,
+ name,
+ should_sync: true,
+ last_synced_at: dayjs(),
+ })),
+ } as ExternalDataSource
+ let results = [source]
+ useMocks({
+ get: {
+ '/api/projects/:team_id/external_data_sources/': () => [
+ 200,
+ { count: results.length, next: null, previous: null, results },
+ ],
+ },
+ })
+ logic = marketingAnalyticsLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['reloadAll']).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.loadSources()).toFinishAllListeners()
+ results = [{ ...source, status: ExternalDataJobStatus.Completed }]
+ await expectLogic(logic, () => logic.actions.loadSources())
+ .toFinishAllListeners()
+ .toNotHaveDispatchedActions(['reloadAll'])
+ .toDispatchActions(['loadDatabase', 'loadSourceValidation'])
+ results = []
+ await expectLogic(logic, () => logic.actions.loadSources())
+ .toFinishAllListeners()
+ .toDispatchActions(['reloadAll'])
+ })
+
it('shows validation errors for the affected connection and clears them after reload', async () => {
let errors: Record<string, string[]> = {}
useMocks({
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
index 8a65b7784720..6724bf8b2cc6 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
@@ -394,6 +394,7 @@ export interface marketingAnalyticsLogicValues {
externalTables: ExternalTable[]
hasNoConfiguredSources: boolean
hasSources: boolean
+ hasSyncedMarketingSources: boolean
includeConversionGoals: boolean
initialized: boolean
integrationFilter: IntegrationFilter
@@ -588,7 +589,9 @@ export interface marketingAnalyticsLogicActions {
setInitialized: () => {
value: true
}
- setIntegrationFilter: (integrationFilter: IntegrationFilter) => { integrationFilter: IntegrationFilter }
+ setIntegrationFilter: (integrationFilter: IntegrationFilter) => {
+ integrationFilter: IntegrationFilter
+ }
setOptionsOpen: (optionsOpen: boolean) => {
optionsOpen: boolean
}
@@ -734,6 +737,7 @@ export interface marketingAnalyticsLogicMeta {
loading: boolean,
dataWarehouseTables: DatabaseSchemaDataWarehouseTable[]
) => boolean
+ hasSyncedMarketingSources: (validExternalTables: ExternalTable[], validNativeSources: NativeSource[]) => boolean
hasSources: (validExternalTables: ExternalTable[], validNativeSources: NativeSource[]) => boolean
allExternalTablesWithStatus: (
externalTables: ExternalTable[],
@@ -1402,6 +1406,19 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
return validExternalTables.length === 0 && validNativeSources.length === 0
},
],
+ hasSyncedMarketingSources: [
+ (s) => [s.validExternalTables, s.validNativeSources],
+ (externalTables: ExternalTable[], nativeSources: NativeSource[]): boolean =>
+ externalTables.length > 0 ||
+ nativeSources.some(({ source }) => {
+ const requiredFields =
+ NEEDED_FIELDS_FOR_NATIVE_MARKETING_ANALYTICS[source.source_type as NativeMarketingSource]
+ return requiredFields.every((fieldName) => {
+ const schema = findSchemaByFieldName(source.schemas, fieldName, source.source_type)
+ return schema?.should_sync && !!schema.last_synced_at
+ })
+ }),
+ ],
hasSources: [
(s) => [s.validExternalTables, s.validNativeSources],
(validExternalTables: ExternalTable[], validNativeSources: NativeSource[]): boolean =>
@@ -1666,7 +1683,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
})
},
})),
- listeners(({ actions, values }) => {
+ listeners(({ actions, values, cache }) => {
const trackDashboardInteraction = (): void => {
// Only track after initialization to avoid tracking initial render/setup
if (!values.initialized) {
@@ -1776,9 +1793,38 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
}
}
- // Refresh warehouse tables to pick up new source tables, then reload queries.
- actions.loadDatabase()
- actions.reloadAll()
+ const sourceConfigurationKey = JSON.stringify(
+ (values.dataWarehouseSources?.results ?? []).map((source) => [
+ source.id,
+ source.source_type,
+ source.prefix,
+ source.schemas.map((schema) => [
+ schema.id,
+ schema.name,
+ schema.should_sync,
+ !!schema.last_synced_at,
+ schema.table?.name,
+ schema.table?.hogql_name,
+ ]),
+ ])
+ )
+ const sourceSyncKey = JSON.stringify(
+ (values.dataWarehouseSources?.results ?? []).map((source) => [
+ source.id,
+ source.status,
+ source.schemas.map((schema) => [schema.id, schema.last_synced_at]),
+ ])
+ )
+ // Health polling must not force every dashboard query while only sync status changes.
+ if (cache.sourceConfigurationKey !== sourceConfigurationKey) {
+ cache.sourceConfigurationKey = sourceConfigurationKey
+ actions.loadDatabase()
+ actions.reloadAll()
+ } else if (cache.sourceSyncKey !== sourceSyncKey) {
+ actions.loadDatabase()
+ actions.loadSourceValidation()
+ }
+ cache.sourceSyncKey = sourceSyncKey
// Mark as initialized after initial data load to enable interaction tracking
if (!values.initialized) {
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.test.ts
index a74bbe64e76f..e4edc3dc3810 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.test.ts
@@ -372,10 +372,7 @@ describe('setupPlanLogic', () => {
})
})
- it('asks the server for a fresh scan only when the user asks for one', async () => {
- // The mount-time load is happy with the server's short cache — that's what
- // stops section navigation re-running six ClickHouse queries. An explicit
- // Rescan has to bypass it or the button looks broken.
+ it('allows manual scans once per hour after the initial scan', async () => {
const urls: string[] = []
useMocks({
get: {
@@ -387,9 +384,15 @@ describe('setupPlanLogic', () => {
})
await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
- await expectLogic(logic, () => logic.actions.loadSetupPlan({ refresh: true })).toFinishAllListeners()
-
- expect(urls[0]).not.toContain('refresh')
+ await expectLogic(logic, () => logic.actions.rescanSources()).toFinishAllListeners()
+ expect(urls).toHaveLength(1)
+ const clock = jest.spyOn(Date, 'now').mockReturnValue(Date.now() + 60 * 60 * 1000 + 1)
+ await expectLogic(logic, () => logic.actions.rescanSources()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.rescanSources()).toFinishAllListeners()
+ clock.mockRestore()
+ expect(urls).toHaveLength(2)
+
+ expect(new URL(urls[0]).searchParams.get('refresh')).toBe('false')
expect(urls[1]).toContain('refresh=true')
})
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.ts
index 4985fb271772..36f7732d6f5d 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
@@ -6,6 +6,7 @@ import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
+import { marketingAnalyticsSetupPlanRetrieve } from 'products/marketing_analytics/frontend/generated/api'
import type {
CapabilityReadinessApi,
SetupPlanResponseApi,
@@ -97,9 +98,12 @@ export interface setupPlanLogicValues {
readiness: CapabilityReadiness[]
reviewingSuggestion: Suggestion | null
safeBatch: Suggestion[]
+ scanClock: number
setupPlan: SetupPlanResponse | null
setupPlanLoading: boolean
showDismissed: boolean
+ sourceScanDisabledReason: string | null
+ sourceScanTimes: Record<number, number>
suggestions: Suggestion[]
truncated: boolean
visibleSuggestions: Suggestion[]
@@ -163,6 +167,16 @@ export interface setupPlanLogicActions {
markApplied: (ids: string[]) => {
ids: string[]
}
+ recordSourceScan: (
+ teamId: number,
+ now: number
+ ) => {
+ now: number
+ teamId: number
+ }
+ rescanSources: () => {
+ value: true
+ }
restoreAllDismissed: () => {
value: true
}
@@ -189,6 +203,9 @@ export interface setupPlanLogicActions {
applying: boolean
ids: string[]
}
+ setScanClock: (now: number) => {
+ now: number
+ }
toggleShowDismissed: () => {
value: true
}
@@ -197,6 +214,11 @@ export interface setupPlanLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface setupPlanLogicMeta {
__keaTypeGenInternalSelectorTypes: {
+ sourceScanDisabledReason: (
+ sourceScanTimes: Record<number, number>,
+ currentTeamId: number | null,
+ scanClock: number
+ ) => string | null
suggestions: (setupPlan: SetupPlanResponse | null) => Suggestion[]
readiness: (setupPlan: SetupPlanResponse | null) => CapabilityReadiness[]
degraded: (setupPlan: SetupPlanResponse | null) => string[]
@@ -234,6 +256,9 @@ export const setupPlanLogic = kea<setupPlanLogicType>([
],
})),
actions({
+ rescanSources: true,
+ setScanClock: (now: number) => ({ now }),
+ recordSourceScan: (teamId: number, now: number) => ({ teamId, now }),
applySuggestion: (suggestion: Suggestion) => ({ suggestion }),
applyAllSafe: true,
applyOps: (
@@ -274,25 +299,28 @@ export const setupPlanLogic = kea<setupPlanLogicType>([
setupPlan: [
null as SetupPlanResponse | null,
{
- /** `refresh` forces a fresh scan past the server's short cache.
+ /** `refresh` forces a fresh scan past the server's event scan cache.
*
* The mount-time load is happy with a cached plan — that's the whole
* point of the cache, so switching sections doesn't re-run six
* ClickHouse queries. An explicit Rescan click is a request for
* current data and has to mean it, or the button looks broken. */
loadSetupPlan: async ({ refresh } = { refresh: false }) => {
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
- const response = await api.get(
- `api/projects/${values.currentTeamId}/marketing_analytics/setup_plan${
- refresh ? '?refresh=true' : ''
- }`
- )
+ const response = await marketingAnalyticsSetupPlanRetrieve(String(values.currentTeamId), {
+ refresh,
+ })
return response as SetupPlanResponse
},
},
],
})),
reducers({
+ scanClock: [Date.now(), { setScanClock: (_, { now }) => now }],
+ sourceScanTimes: [
+ {} as Record<number, number>,
+ { persist: true },
+ { recordSourceScan: (state, { teamId, now }) => ({ ...state, [teamId]: now }) },
+ ],
applyingIds: [
[] as string[],
{
@@ -361,6 +389,13 @@ export const setupPlanLogic = kea<setupPlanLogicType>([
],
}),
selectors({
+ sourceScanDisabledReason: [
+ (s) => [s.sourceScanTimes, s.currentTeamId, s.scanClock],
+ (times: Record<number, number>, teamId: number | null, now: number): string | null => {
+ const remaining = (times[teamId ?? 0] ?? 0) + 60 * 60 * 1000 - now
+ return remaining > 0 ? `You can scan again in ${Math.ceil(remaining / 60000)} minutes.` : null
+ },
+ ],
suggestions: [(s) => [s.setupPlan], (plan: SetupPlanResponse | null): Suggestion[] => plan?.suggestions ?? []],
readiness: [
(s) => [s.setupPlan],
@@ -412,6 +447,22 @@ export const setupPlanLogic = kea<setupPlanLogicType>([
],
}),
listeners(({ actions, values }) => ({
+ rescanSources: () => {
+ actions.setScanClock(Date.now())
+ if (!values.setupPlanLoading && !values.sourceScanDisabledReason) {
+ actions.loadSetupPlan({ refresh: true })
+ }
+ },
+ loadSetupPlanSuccess: ({ setupPlan, payload }) => {
+ if (
+ !setupPlan.degraded.length &&
+ values.currentTeamId !== null &&
+ (payload?.refresh || !values.sourceScanTimes[values.currentTeamId])
+ ) {
+ actions.recordSourceScan(values.currentTeamId, Date.now())
+ actions.setScanClock(Date.now())
+ }
+ },
reviewSuggestion: ({ suggestion }) => {
if (suggestion) {
posthog.capture('marketing analytics setup suggestion reviewed', {
@@ -650,4 +701,11 @@ export const setupPlanLogic = kea<setupPlanLogicType>([
}
},
})),
+ afterMount(({ actions, cache }) => {
+ actions.setScanClock(Date.now())
+ cache.disposables.add(() => {
+ const timer = setInterval(() => actions.setScanClock(Date.now()), 30_000)
+ return () => clearInterval(timer)
+ }, 'sourceScanClock')
+ }),
])
diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.py
index c28303ac8fff..d48a1572c714 100644
--- a/products/marketing_analytics/backend/api.py
+++ b/products/marketing_analytics/backend/api.py
@@ -97,8 +97,8 @@ from products.warehouse_sources.backend.facade.models import DataWarehouseTable
logger = structlog.get_logger(__name__)
-def _setup_enabled(request: Request, team: Team) -> bool:
- """Evaluate the Setup flag once per request.
+def _setup_enabled(request: Request, team: Team, *, include_onboarding: bool = False) -> bool:
+ """Evaluate eligible marketing flags once per request.
Evaluated for the requesting person, because the flag's release conditions target
people and the frontend renders the Setup tab off that same per-person answer.
@@ -107,7 +107,8 @@ def _setup_enabled(request: Request, team: Team) -> bool:
condition matches too. Cached on the request because a second call in the same one
would fire a redundant `$feature_flag_called`.
"""
- cached = getattr(request, "_ma_setup_flag", None)
+ cache_attribute = "_ma_onboarding_flag" if include_onboarding else "_ma_setup_flag"
+ cached = getattr(request, cache_attribute, None)
if cached is not None:
return cached
person_properties = {}
@@ -124,9 +125,13 @@ def _setup_enabled(request: Request, team: Team) -> bool:
person_properties=person_properties,
group_properties={"organization": {"id": str(team.organization.id)}},
)
- for flag in ("marketing-analytics-setup", "new-marketing-analytics-dashboard")
+ for flag in (
+ "marketing-analytics-setup",
+ "new-marketing-analytics-dashboard",
+ *(("marketing-analytics-source-onboarding",) if include_onboarding else ()),
+ )
)
- request._ma_setup_flag = enabled # type: ignore[attr-defined]
+ setattr(request, cache_attribute, enabled)
return enabled
@@ -1631,7 +1636,7 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
@action(methods=["GET"], detail=False, url_path="setup_plan", required_scopes=["marketing_analytics:read"])
def setup_plan(self, request: Request, *args, **kwargs) -> Response:
# 404 rather than 403: an unreleased endpoint should look absent, not forbidden.
- if not _setup_enabled(request, self.team):
+ if not _setup_enabled(request, self.team, include_onboarding=True):
raise NotFound("Marketing analytics setup is not enabled for this project.")
date_from = request.validated_query_data["date_from"]
@@ -1648,6 +1653,7 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
self.team,
date_from=date_from,
user=user,
+ refresh_source_scan=request.validated_query_data["refresh"],
)
# `model_dump(mode="json")` so the Pydantic op models inside each suggestion
# come out as plain JSON — the serializer exposes them as JSONField.
diff --git a/products/marketing_analytics/backend/services/attribution_health.py b/products/marketing_analytics/backend/services/attribution_health.py
index 42a008a14132..1316a8237cdc 100644
--- a/products/marketing_analytics/backend/services/attribution_health.py
+++ b/products/marketing_analytics/backend/services/attribution_health.py
@@ -10,6 +10,7 @@ from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta
from typing import Any, cast
+from django.core.cache import cache
from django.utils import timezone
import structlog
@@ -124,6 +125,8 @@ async def get_attribution_health(
source_type: str | None = None,
lookback_days: int = DEFAULT_LOOKBACK_DAYS,
custom_source_mappings: dict | None = None,
+ cache_scan: bool = False,
+ refresh_scan: bool = False,
) -> AttributionHealthResponse:
"""Aggregate UTM-tagged event counts per native integration over `lookback_days`.
@@ -132,7 +135,7 @@ async def get_attribution_health(
`custom_source_mappings` lets callers pass a pre-loaded config to avoid a
Postgres roundtrip; when None, the service loads it itself.
"""
- rows = await _fetch_utm_groups(team, lookback_days=lookback_days)
+ rows = await _fetch_utm_groups(team, lookback_days=lookback_days, cache_scan=cache_scan, refresh_scan=refresh_scan)
if custom_source_mappings is None:
alias_map = await _build_team_alias_map(team)
else:
@@ -324,7 +327,9 @@ def _platform_paid_expressions(paid_medium: ast.Expr) -> dict[NativeIntegration,
@database_sync_to_async
-def _fetch_utm_groups(team: Team, *, lookback_days: int) -> list[_UtmRow]:
+def _fetch_utm_groups(
+ team: Team, *, lookback_days: int, cache_scan: bool = False, refresh_scan: bool = False
+) -> list[_UtmRow]:
"""HogQL aggregation of utm_source counts and latest timestamp within the window.
Intentionally not restricted to `$pageview` — conversion goals are often custom
@@ -334,6 +339,14 @@ def _fetch_utm_groups(team: Team, *, lookback_days: int) -> list[_UtmRow]:
with a wrong clock can stamp an event years ahead and make `max(timestamp)` report a
last-seen date in the future.
"""
+ cache_key = f"marketing_analytics:source_scan:v1:{team.pk}:{lookback_days}"
+ scan_time_key = f"{cache_key}:scanned_at"
+ last_scan = cache.get(scan_time_key) if cache_scan else None
+ within_cooldown = last_scan is not None and timezone.now() - last_scan < timedelta(hours=1)
+ if cache_scan and (not refresh_scan or within_cooldown):
+ cached_rows = cache.get(cache_key)
+ if cached_rows is not None:
+ return cast(list[_UtmRow], cached_rows)
now = timezone.now()
since = now - timedelta(days=lookback_days)
paid_medium = parse_expr(
@@ -387,6 +400,9 @@ def _fetch_utm_groups(team: Team, *, lookback_days: int) -> list[_UtmRow]:
tagged_medium_count=int(tagged_count or 0),
)
)
+ if cache_scan:
+ cache.set(cache_key, rows, 7 * 24 * 60 * 60)
+ cache.set(scan_time_key, timezone.now(), 7 * 24 * 60 * 60)
return rows
diff --git a/products/marketing_analytics/backend/services/marketing_diagnostic.py b/products/marketing_analytics/backend/services/marketing_diagnostic.py
index c7599890f8db..0d6f371faf21 100644
--- a/products/marketing_analytics/backend/services/marketing_diagnostic.py
+++ b/products/marketing_analytics/backend/services/marketing_diagnostic.py
@@ -114,6 +114,8 @@ async def get_marketing_diagnostic(
include_conversion_goals: bool = True,
attribution_lookback_days: int = 7,
user: User | None = None,
+ cache_source_scan: bool = False,
+ refresh_source_scan: bool = False,
) -> MarketingDiagnosticResponse:
"""Fetch all per-domain signals in parallel and combine into a unified view.
@@ -130,6 +132,8 @@ async def get_marketing_diagnostic(
source_type=source_type,
lookback_days=attribution_lookback_days,
custom_source_mappings=custom_source_mappings,
+ cache_scan=cache_source_scan,
+ refresh_scan=refresh_source_scan,
),
]
if include_conversion_goals:
diff --git a/products/marketing_analytics/backend/services/setup_plan.py b/products/marketing_analytics/backend/services/setup_plan.py
index 925cde544200..fa81a3920fcd 100644
--- a/products/marketing_analytics/backend/services/setup_plan.py
+++ b/products/marketing_analytics/backend/services/setup_plan.py
@@ -113,6 +113,7 @@ async def get_setup_plan(
*,
date_from: str = "-30d",
user: User | None = None,
+ refresh_source_scan: bool = False,
) -> SetupPlan:
"""Build the ranked setup plan for a team."""
date_range = QueryDateRange(
@@ -123,8 +124,16 @@ async def get_setup_plan(
)
results = await asyncio.gather(
- get_marketing_diagnostic(team, include_conversion_goals=True, user=user),
- get_attribution_health(team, lookback_days=ATTRIBUTION_LOOKBACK_DAYS),
+ get_marketing_diagnostic(
+ team,
+ include_conversion_goals=True,
+ user=user,
+ cache_source_scan=True,
+ refresh_source_scan=refresh_source_scan,
+ ),
+ get_attribution_health(
+ team, lookback_days=ATTRIBUTION_LOOKBACK_DAYS, cache_scan=True, refresh_scan=refresh_source_scan
+ ),
suggest_conversion_goals(team),
get_campaigns_with_spend_async(team, date_range, user=user),
get_utm_campaign_catalogue_async(team, date_range, user=user),
diff --git a/products/marketing_analytics/backend/services/test_attribution_health.py b/products/marketing_analytics/backend/services/test_attribution_health.py
index ffed64a3f0e9..449d12515d68 100644
--- a/products/marketing_analytics/backend/services/test_attribution_health.py
+++ b/products/marketing_analytics/backend/services/test_attribution_health.py
@@ -1,19 +1,22 @@
from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
import pytest
import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, Mock, patch
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, override_settings
from django.utils import timezone
+from asgiref.sync import async_to_sync
from parameterized import parameterized
from posthog.models.team.team import Team
from products.marketing_analytics.backend.services.attribution_health import (
HOGQL_GROUP_LIMIT,
+ AttributionHealthResponse,
_suggest_integration_by_alias_token,
_UtmRow,
get_attribution_health,
@@ -552,3 +555,35 @@ class TestAttributionHealthFutureTimestampClickhouse(ClickhouseTestMixin, BaseTe
assert response.total_events_with_utm == 1
assert google.last_event_with_matching_utm_at is not None
assert google.last_event_with_matching_utm_at <= timezone.now()
+
+
+class TestSourceScanCache(SimpleTestCase):
+ @override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})
+ def test_cached_scan_refresh_and_project_isolation(self) -> None:
+ team = Mock(spec=Team, pk=101)
+ other_team = Mock(spec=Team, pk=102)
+ with patch(
+ "products.marketing_analytics.backend.services.attribution_health.execute_hogql_query",
+ return_value=SimpleNamespace(results=[["facebook", 12, None, 0, 0, 0]]),
+ ) as query:
+
+ def scan(project: Team, *, refresh: bool = False) -> AttributionHealthResponse:
+ return async_to_sync(get_attribution_health)(
+ project, custom_source_mappings={}, cache_scan=True, refresh_scan=refresh
+ )
+
+ assert scan(team).total_events_with_utm == 12
+ query.return_value = SimpleNamespace(results=[["facebook", 24, None, 0, 0, 0]])
+ assert scan(team).total_events_with_utm == 12
+ assert query.call_count == 1
+ assert scan(team, refresh=True).total_events_with_utm == 12
+ assert query.call_count == 1
+ with time_machine.travel(timezone.now() + timedelta(hours=1, seconds=1)):
+ assert scan(team, refresh=True).total_events_with_utm == 24
+ assert query.call_count == 2
+ assert scan(other_team).total_events_with_utm == 24
+ assert query.call_count == 3
+ query.return_value = SimpleNamespace(results=[["facebook", 36, None, 0, 0, 0]])
+ with time_machine.travel(timezone.now() + timedelta(days=8)):
+ assert scan(team).total_events_with_utm == 36
+ assert query.call_count == 4
diff --git a/products/marketing_analytics/backend/test_api_setup_plan.py b/products/marketing_analytics/backend/test_api_setup_plan.py
index 3d55ebc29ac5..3b4f131e285b 100644
--- a/products/marketing_analytics/backend/test_api_setup_plan.py
+++ b/products/marketing_analytics/backend/test_api_setup_plan.py
@@ -153,17 +153,33 @@ class TestSetupPlanFeatureFlag(APIBaseTest):
self.url = f"/api/projects/{self.team.pk}/marketing_analytics/setup_plan"
cache.clear()
- @parameterized.expand([(False, False), (False, True), (True, False), (True, True)])
- def test_setup_availability(self, setup: bool, dashboard: bool) -> None:
- flags = {"marketing-analytics-setup": setup, "new-marketing-analytics-dashboard": dashboard}
+ @parameterized.expand(
+ [(False, False, False), (False, False, True), (False, True, False), (True, False, False), (True, True, True)]
+ )
+ def test_setup_availability(self, setup: bool, dashboard: bool, onboarding: bool) -> None:
+ flags = {
+ "marketing-analytics-setup": setup,
+ "new-marketing-analytics-dashboard": dashboard,
+ "marketing-analytics-source-onboarding": onboarding,
+ }
with (
patch(_FLAG_TARGET, side_effect=lambda flag, *args, **kwargs: flags[flag]),
patch(_PLAN_TARGET, return_value=_plan()) as build,
):
response = self.client.get(self.url)
- assert response.status_code == (200 if setup or dashboard else 404)
- assert build.call_count == int(setup or dashboard)
+ assert response.status_code == (200 if setup or dashboard or onboarding else 404)
+ assert build.call_count == int(setup or dashboard or onboarding)
+
+ def test_marketing_access_does_not_enable_source_onboarding(self) -> None:
+ with (
+ patch(_FLAG_TARGET, side_effect=lambda flag, *args, **kwargs: flag == "marketing-analytics"),
+ patch(_PLAN_TARGET) as build,
+ ):
+ response = self.client.get(self.url)
+
+ assert response.status_code == 404
+ build.assert_not_called()
def test_the_flag_is_evaluated_once_per_request(self):
# A second call in the same request would fire a redundant `$feature_flag_called`.
@@ -230,6 +246,7 @@ class TestSetupPlanCaching(APIBaseTest):
self.client.get(f"{self.url}?refresh=true")
assert build.call_count == 2
+ assert build.call_args.kwargs["refresh_source_scan"] is True
def test_a_different_window_is_a_different_question(self):
with patch(_PLAN_TARGET, return_value=_clean_plan()) as build:
diff --git a/products/marketing_analytics/frontend/emptyState/marketingAnalyticsSetupLogic.ts b/products/marketing_analytics/frontend/emptyState/marketingAnalyticsSetupLogic.ts
index e4eaeae2f2e8..08eb4521bf00 100644
--- a/products/marketing_analytics/frontend/emptyState/marketingAnalyticsSetupLogic.ts
+++ b/products/marketing_analytics/frontend/emptyState/marketingAnalyticsSetupLogic.ts
@@ -6,6 +6,7 @@ import type { ProductSetupStatus } from 'lib/components/ProductEmptyState/types'
import { marketingAnalyticsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
import { ProductKey } from '~/queries/schema/schema-general'
+import { ExternalDataSource } from '~/types'
// If the sources never finish loading, fail open to the scene rather than
// stranding the gate on its spinner.
@@ -15,6 +16,7 @@ const LOADING_FALLBACK_MS = 10000
export interface marketingAnalyticsSetupLogicValues {
hasSources: boolean // marketingAnalyticsLogic
loading: boolean // marketingAnalyticsLogic
+ nativeSources: ExternalDataSource[] // marketingAnalyticsLogic
setupStatus: ProductSetupStatus // productSetupStatusLogic
}
@@ -32,9 +34,8 @@ export type marketingAnalyticsSetupLogicType = MakeLogicType<
/**
* Setup detection for the marketing analytics empty state. "Set up" means at
- * least one valid ad source (a native integration, or a warehouse table with
- * its UTM columns mapped) - the same `hasSources` the scene's own onboarding
- * keys off. The value comes from the scene logic (which sceneLogic keeps
+ * least one configured native ad source, including its first sync, or a warehouse
+ * table with its UTM columns mapped. The value comes from the scene logic (which sceneLogic keeps
* mounted while the gate renders), so this logic just waits for its sources
* to finish loading and mirrors the verdict.
*/
@@ -46,26 +47,35 @@ export const marketingAnalyticsSetupLogic = kea<marketingAnalyticsSetupLogicType
productSetupStatusLogic({ productKey: ProductKey.MARKETING_ANALYTICS }),
['status as setupStatus'],
marketingAnalyticsLogic,
- ['hasSources', 'loading'],
+ ['hasSources', 'nativeSources', 'loading'],
],
actions: [productSetupStatusLogic({ productKey: ProductKey.MARKETING_ANALYTICS }), ['setDetectedStatus']],
})),
subscriptions(({ actions, values }) => ({
loading: (loading: boolean) => {
if (!loading) {
- actions.setDetectedStatus(values.hasSources ? 'has-data' : 'needs-setup')
+ actions.setDetectedStatus(
+ values.hasSources || values.nativeSources.length > 0 ? 'has-data' : 'needs-setup'
+ )
+ }
+ },
+ nativeSources: () => {
+ if (!values.loading) {
+ actions.setDetectedStatus(
+ values.hasSources || values.nativeSources.length > 0 ? 'has-data' : 'needs-setup'
+ )
}
},
hasSources: (hasSources: boolean) => {
// Covers a source configured from the wizard while this stays mounted.
if (!values.loading) {
- actions.setDetectedStatus(hasSources ? 'has-data' : 'needs-setup')
+ actions.setDetectedStatus(hasSources || values.nativeSources.length > 0 ? 'has-data' : 'needs-setup')
}
},
})),
afterMount(({ actions, values, cache }) => {
if (!values.loading) {
- actions.setDetectedStatus(values.hasSources ? 'has-data' : 'needs-setup')
+ actions.setDetectedStatus(values.hasSources || values.nativeSources.length > 0 ? 'has-data' : 'needs-setup')
return
}
cache.disposables.add(() => {