:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(marketing-analytics): surface source validation errors (#107000)
Javier Bahamondes2f9bb0d10a0d
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.mdindex 41d56f76c8e3..2c8dac1dca81 100644--- a/docs/published/handbook/engineering/data-warehouse.md+++ b/docs/published/handbook/engineering/data-warehouse.md@@ -31,10 +31,23 @@ Data warehouse syncs continue independently of this flag.Sync `campaigns` and `campaign_insights` to include OpenAI Ads campaign delivery in Marketing analytics.Spend is already in major currency units; the importer adds `currency_code` from the account metadata so reports can convert spend at each bucket date.Existing connections need a full resync of `campaign_insights` to populate currency on historical rows.-Cost tiles are unavailable without the currency column; queries with empty historical currency values stop with a resync message.+Without the currency column, cost tiles are unavailable and the campaign table excludes the source.+The dashboard and source settings show a warning with a link to the affected warehouse source and instructions to fully resync `campaign_insights`.+Queries with empty historical currency values stop with a resync message.Reported conversions and revenue are zero because the importer currently requests delivery metrics only.Ad groups and individual ads are not included in the native integration.+## Source warnings in Marketing analytics++The dashboard and source settings show validation errors for connected native and mapped external sources.+They use the same adapter validators as campaign queries, so warnings follow each integration's supported checks without a separate frontend list of required columns.+Warnings identify the affected connection and link to its settings.+Mapped sources with missing required column mappings remain visible in these warnings until corrected.+The dashboard also shows missing or disabled required tables and running, failed, paused, or cancelled syncs.+Reload the dashboard after correcting the configuration or resyncing a table to refresh validation.+This check uses table metadata and configuration; it does not scan imported rows for data quality issues.+Query execution errors still appear on the affected dashboard tile or table.+## Amazon Ads in Marketing analyticsMarketing analytics support is controlled by the boolean organization flag `marketing-analytics-amazon-ads` and is off by default.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d4514cbbfb1c..7e28a80d2370 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10418,6 +10418,10 @@ snapshots:hash: v1.k794b7964.71ad45e65a5513ff7088e026d8ffb2bf891fb1effddb0e9dbd95ba78b597c3b1.0e6bNu95d2bH_NlZmGGW7oiHJ__aHNSxqzRcxMUA4xMscenes-app-marketing-analytics-freshness--fresh--light:hash: v1.k794b7964.b8d9453c270c310350d2bcf30cdb54cae4da19b8877e8d3206160478eb2dda94.dJpt6MIMxg7mOxiHC6PoqwTGwMfiGrln7SheHTKHTcU+ scenes-app-marketing-analytics-source-status--source-issues--dark:+ hash: v1.k794b7964.f387ac40dbf399676c91b2f6de86c2b169e9aaa86205af692abf51a141ead5d7.3PpHqWiSeMKvXuYLv4lU1yM_tqF38xD4NiUkUX6XW2U+ scenes-app-marketing-analytics-source-status--source-issues--light:+ hash: v1.k794b7964.9bc9c27858206a2c2ecee18b7e72a9b80c91488ab539e78955a62b0254176a8e.gYszI9sP1_uusVkRVzBFdMoACwSmYaBfgxSuUX_pZpQscenes-app-max-ai-logs-query-tool--no-matches--dark:hash: v1.k794b7964.c231a64a00f6dfc8bf5b88c3dab624bad88d347b96be0b2e6b0cc14e1c10e1cc.ScE515QePrAYrJB-UWn5sakLt5cKxQKQQrx_n_uJERIscenes-app-max-ai-logs-query-tool--no-matches--light:diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.tsindex 206cdc863f16..27ffb1c63f76 100644--- a/frontend/src/mocks/handlers.ts+++ b/frontend/src/mocks/handlers.ts@@ -98,6 +98,7 @@ function posthogCORSResponse(info: MockResolverInfo): Response {export const defaultMocks: Mocks = {get: {+ '/api/projects/:team_id/marketing_analytics/source_validation/': { errors_by_source: {} },'/api/projects/:team_id/my_notifications/': EMPTY_PAGINATED_RESPONSE,'/api/projects/:team_id/tasks/': EMPTY_PAGINATED_RESPONSE,'/api/projects/:team_id/actions/': EMPTY_PAGINATED_RESPONSE,diff --git a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsxindex b07417add941..129f070ab393 100644--- a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx+++ b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx@@ -105,6 +105,8 @@ describe('NewMarketingAnalyticsDashboard', () => {responseLoading: false,setupPlan: {},visibleSuggestions: [],+ allAvailableSourcesWithStatus: [],+ sourceValidationError: null,trafficOrderBy: {},trafficChartMetric: 'visitors',trafficChartSeries: { kind: 'EventsNode', event: null, math: 'dau', custom_name: 'Visitors' },@@ -135,6 +137,8 @@ describe('NewMarketingAnalyticsDashboard', () => {responseLoading: false,setupPlan: {},visibleSuggestions: [],+ allAvailableSourcesWithStatus: [],+ sourceValidationError: null,trafficOrderBy: {},trafficChartMetric: 'visitors',trafficChartSeries: { kind: 'EventsNode', event: null, math: 'dau', custom_name: 'Visitors' },diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsSourceStatusBanner.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsSourceStatusBanner.tsxindex b57a239fabb9..fc4160523ec2 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsSourceStatusBanner.tsx+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsSourceStatusBanner.tsx@@ -8,130 +8,58 @@ import { urls } from 'scenes/urls'import { ExternalDataSchemaStatus } from '~/types'import { MarketingSourceStatus, marketingAnalyticsLogic } from '../logic/marketingAnalyticsLogic'--type StatusCount = Record<- | ExternalDataSchemaStatus.Running- | ExternalDataSchemaStatus.Failed- | ExternalDataSchemaStatus.Paused- | MarketingSourceStatus.Warning,- number->--const getStatusCounts = (sources: { status: string }[]): StatusCount => {- const counts: StatusCount = {- [ExternalDataSchemaStatus.Running]: 0,- [ExternalDataSchemaStatus.Failed]: 0,- [ExternalDataSchemaStatus.Paused]: 0,- [MarketingSourceStatus.Warning]: 0,- }-- for (const source of sources) {- if (source.status === ExternalDataSchemaStatus.Running) {- counts[ExternalDataSchemaStatus.Running] += 1- } else if (source.status === ExternalDataSchemaStatus.Failed) {- counts[ExternalDataSchemaStatus.Failed] += 1- } else if (source.status === ExternalDataSchemaStatus.Paused) {- counts[ExternalDataSchemaStatus.Paused] += 1- } else if (source.status === MarketingSourceStatus.Warning) {- counts[MarketingSourceStatus.Warning] += 1- }- }-- return counts-}--const SourceStatusMessage = ({- length,- singularVerb,- pluralVerb,- message,-}: {- length: number- singularVerb: string- pluralVerb: string- message: string-}): JSX.Element | null => {- if (length === 0) {- return null- }- return (- <>- <strong>- {length} source{length > 1 ? 's' : ''} {length > 1 ? pluralVerb : singularVerb} {message}- </strong>- .{' '}- </>- )-}+import { nativeSourceDisplayLabel } from '../logic/utils'export const MarketingAnalyticsSourceStatusBanner = (): JSX.Element | null => {- const { allAvailableSourcesWithStatus } = useValues(marketingAnalyticsLogic)+ const { allAvailableSourcesWithStatus, sourceValidationError } = useValues(marketingAnalyticsLogic)const sourcesWithIssues = allAvailableSourcesWithStatus.filter((source) =>source.status === 'Running' ||source.status === 'Failed' ||source.status === 'Paused' ||+ source.status === 'Cancelled' ||+ source.status === MarketingSourceStatus.Error ||source.status === MarketingSourceStatus.Warning)- if (sourcesWithIssues.length === 0) {+ if (sourcesWithIssues.length === 0 && !sourceValidationError) {return null}- const statusCounts = getStatusCounts(sourcesWithIssues)- const hasErrors = statusCounts[ExternalDataSchemaStatus.Failed] > 0- const hasWarnings = statusCounts[MarketingSourceStatus.Warning] > 0+ const hasErrors = sourcesWithIssues.some(+ ({ status }) => status === ExternalDataSchemaStatus.Failed || status === MarketingSourceStatus.Error+ )+ const hasWarnings =+ sourceValidationError ||+ sourcesWithIssues.some(+ ({ status }) => status === MarketingSourceStatus.Warning || status === ExternalDataSchemaStatus.Cancelled+ )const bannerType = hasErrors ? 'error' : hasWarnings ? 'warning' : 'info'return (<LemonBanner type={bannerType} className="mb-2 mt-4">- {sourcesWithIssues.length === 1 ? (- <>- <strong>{sourcesWithIssues[0].name}</strong>- {sourcesWithIssues[0].status === MarketingSourceStatus.Warning- ? `: ${sourcesWithIssues[0].statusMessage}`- : ` is currently ${- sourcesWithIssues[0].status === 'Running'- ? 'syncing'- : sourcesWithIssues[0].status === 'Failed'- ? 'failed'- : 'paused'- }. ${sourcesWithIssues[0].statusMessage}`}- </>- ) : (- <>- <SourceStatusMessage- length={statusCounts[MarketingSourceStatus.Warning]}- singularVerb="has"- pluralVerb="have"- message="missing required tables for import"- />- <SourceStatusMessage- length={statusCounts[ExternalDataSchemaStatus.Running]}- singularVerb="is"- pluralVerb="are"- message="syncing"- />- <SourceStatusMessage- length={statusCounts[ExternalDataSchemaStatus.Failed]}- singularVerb="has"- pluralVerb="have"- message="failed while syncing"- />- <SourceStatusMessage- length={statusCounts[ExternalDataSchemaStatus.Paused]}- singularVerb="is"- pluralVerb="are"- message="paused"- />- </>- )}{' '}- Check{' '}- <Link to={urls.settings('environment-marketing-analytics')} target="_blank">- marketing analytics settings- </Link>{' '}- for more details.+ <div className="space-y-2 min-w-0 break-words">+ {sourceValidationError && (+ <div>Could not check source configuration. Reload the dashboard to try again.</div>+ )}+ {sourcesWithIssues.map((source) => (+ <div key={source.id}>+ <Link+ to={+ source.type === 'native'+ ? urls.dataWarehouseSource(`managed-${source.id}`)+ : urls.settings('environment-marketing-analytics')+ }+ data-attr="marketing-source-status-settings"+ >+ {source.type === 'native' ? nativeSourceDisplayLabel(source.source_type) : source.name}+ {source.prefix ? ` (${source.prefix})` : ''}+ </Link>+ <span>{`: ${source.statusMessage}`}</span>+ </div>+ ))}+ </div></LemonBanner>)}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.tsindex 86950cde9bbd..ea0f21c34ba1 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@@ -10,6 +10,7 @@ import { databaseTableListLogic } from 'scenes/data-management/database/databaseimport { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { useMocks } from '~/mocks/jest'import {ConversionGoalFilter,MARKETING_INTEGRATION_CONFIGS,@@ -24,13 +25,15 @@ import {MarketingAnalyticsBaseColumns,MarketingAnalyticsColumnsSchemaNames,NodeKind,+ SourceMap,WebAnalyticsPropertyFilters,} from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { ExternalDataSource, PropertyFilterType, PropertyOperator } from '~/types'+import { ExternalDataSchemaStatus, ExternalDataSource, PropertyFilterType, PropertyOperator } from '~/types'import {MarketingAnalyticsTab,+ MarketingSourceStatus,MarketingDashboardView,SetupSection,marketingAnalyticsLogic,@@ -389,6 +392,159 @@ describe('marketingAnalyticsLogic', () => {expect(logic.values.unconfiguredNativeSources).toEqual([])})+ it('shows validation errors for the affected connection and clears them after reload', async () => {+ let errors: Record<string, string[]> = {}+ useMocks({+ get: {+ '/api/projects/:team_id/marketing_analytics/source_validation/': () => [+ 200,+ { errors_by_source: errors },+ ],+ },+ })+ logic = marketingAnalyticsLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_OPENAI_ADS]: true })+ const sources = ['outdated', 'current'].map(+ (id) =>+ ({+ id,+ source_type: 'OpenAIAds',+ schemas: ['campaigns', 'campaign_insights'].map((name) => ({+ id: `${id}-${name}`,+ name,+ should_sync: true,+ status: ExternalDataSchemaStatus.Completed,+ })),+ }) as ExternalDataSource+ )+ await expectLogic(logic, () =>+ logic.actions.loadSourcesSuccess({ count: 2, next: null, previous: null, results: sources })+ ).toFinishAllListeners()+ expect(logic.values.allAvailableSourcesWithStatus.every(({ status }) => status === 'Completed')).toBe(true)++ errors = { outdated: ["Missing 'currency_code' in 'campaign_insights'.", "Missing 'name' in 'campaigns'."] }+ await expectLogic(logic, () => logic.actions.reloadAll()).toFinishAllListeners()+ for (const sourcesWithStatus of [+ logic.values.allAvailableSourcesWithStatus,+ logic.values.allExternalTablesWithStatus,+ ]) {+ expect(sourcesWithStatus.find((source) => source.id === 'outdated')).toMatchObject({+ status: MarketingSourceStatus.Warning,+ statusMessage: expect.stringContaining(errors.outdated.join(' ')),+ })+ expect(sourcesWithStatus.find((source) => source.id === 'current')?.status).toBe('Completed')+ }+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_OPENAI_ADS]: false })+ expect(logic.values.allAvailableSourcesWithStatus).toEqual([])+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_OPENAI_ADS]: true })+ errors = {}+ await expectLogic(logic, () => logic.actions.reloadAll()).toFinishAllListeners()+ for (const sourcesWithStatus of [+ logic.values.allAvailableSourcesWithStatus,+ logic.values.allExternalTablesWithStatus.filter((source) => sources.some(({ id }) => id === source.id)),+ ]) {+ expect(sourcesWithStatus.map(({ status }) => status)).toEqual(['Completed', 'Completed'])+ }+ useMocks({+ get: { '/api/projects/:team_id/marketing_analytics/source_validation/': () => [500, {}] },+ })+ await expectLogic(logic, () => logic.actions.loadSourceValidation()).toFinishAllListeners()+ expect(logic.values.sourceValidationError).not.toBeNull()+ useMocks({+ get: {+ '/api/projects/:team_id/marketing_analytics/source_validation/': () => [200, { errors_by_source: {} }],+ },+ })+ await expectLogic(logic, () => logic.actions.loadSourceValidation()).toFinishAllListeners()+ expect(logic.values.sourceValidationError).toBeNull()+ })++ it.each(['managed', 'self-managed'])('shows invalid mappings for a %s source until corrected', async (type) => {+ const tableId = 'example-table'+ const sourceId = type === 'managed' ? 'example-schema' : tableId+ let errors: Record<string, string[]> = { [sourceId]: ['Missing required column mapping: cost'] }+ useMocks({+ get: {+ '/api/projects/:team_id/marketing_analytics/source_validation/': () => [+ 200,+ { errors_by_source: errors },+ ],+ },+ })+ logic = marketingAnalyticsLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ databaseTableListLogic.actions.loadDatabaseSuccess({+ tables: {+ example_campaigns: {+ id: tableId,+ name: 'example_campaigns',+ type: 'data_warehouse',+ url_pattern: 'https://example.s3.amazonaws.com/campaigns',+ ...(type === 'managed'+ ? {+ schema: {+ id: sourceId,+ name: 'example_campaigns',+ should_sync: true,+ incremental: false,+ status: ExternalDataSchemaStatus.Completed,+ },+ source: {+ id: 'example-source',+ source_type: 'BigQuery',+ status: 'Completed',+ prefix: '',+ },+ }+ : {}),+ fields: {+ cost: { name: 'cost', hogql_value: 'cost', type: 'float', schema_valid: true },+ },+ } satisfies DatabaseSchemaDataWarehouseTable,+ },+ joins: [],+ })++ for (const sourceMap of [{}, { campaign: 'campaign' }] as SourceMap[]) {+ await expectLogic(logic, () =>+ teamLogic.actions.loadCurrentTeamSuccess({+ ...teamLogic.values.currentTeam!,+ marketing_analytics_config: { sources_map: { [sourceId]: sourceMap } },+ })+ ).toFinishAllListeners()+ expect(logic.values.validExternalTables).toEqual([])+ expect(logic.values.allAvailableSources).toEqual([])+ expect(logic.values.allAvailableSourcesWithStatus).toEqual([+ expect.objectContaining({+ id: sourceId,+ status: MarketingSourceStatus.Warning,+ statusMessage: expect.stringContaining(errors[sourceId][0]),+ }),+ ])+ }+ await expectLogic(logic, () =>+ teamLogic.actions.loadCurrentTeamSuccess({+ ...teamLogic.values.currentTeam!,+ marketing_analytics_config: {+ sources_map: {+ [sourceId]: Object.fromEntries(+ Object.values(MarketingAnalyticsColumnsSchemaNames).map((name) => [name, name])+ ) as SourceMap,+ },+ },+ })+ ).toFinishAllListeners()+ errors = {}+ await expectLogic(logic, () => logic.actions.reloadAll()).toFinishAllListeners()+ expect(logic.values.validExternalTables).toHaveLength(1)+ expect(logic.values.allAvailableSourcesWithStatus).toEqual([+ expect.objectContaining({ id: sourceId, status: ExternalDataSchemaStatus.Completed }),+ ])+ })+it('keeps the selection and drops an unknown key from a filter saved by an older build', async () => {localStorage.setItem(STORAGE_KEY,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.tsindex 51ce2d3bb763..e1ddf2a00e72 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@@ -10,6 +10,7 @@ import {reducers,selectors,} from 'kea'+import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'import posthog from 'posthog-js'@@ -50,6 +51,8 @@ import { ChartDisplayType } from '~/types'import { mapUrlToProvider } from 'products/data_warehouse/frontend/shared/components/SourceIcon'import { sourceManagementLogic } from 'products/data_warehouse/frontend/shared/logics/sourceManagementLogic'+import { marketingAnalyticsSourceValidationRetrieve } from 'products/marketing_analytics/frontend/generated/api'+import type { SourceValidationApi } from 'products/marketing_analytics/frontend/generated/api.schemas'import type { PaginatedResponse } from '../../../../../../lib/api'import type { FeatureFlagsSet } from '../../../../../../lib/logic/featureFlagLogic'@@ -189,8 +192,16 @@ export type SourceStatus = ExternalDataSchemaStatus | MarketingSourceStatusfunction getSourceStatus(source: { id: string; name: string; type: string; prefix?: string },nativeSources: ExternalDataSource[],- validExternalTables: ExternalTable[]+ validExternalTables: ExternalTable[],+ validationErrors: SourceValidationApi['errors_by_source']): { status: SourceStatus; message: string } {+ const errors = validationErrors[source.id]+ const validationWarning = errors?.length+ ? {+ status: MarketingSourceStatus.Warning,+ message: `${errors.join(' ')} This source is excluded from the campaign table. ${source.type === 'native' ? 'Review its settings and fully resync the affected tables.' : 'Review its column mapping and table configuration.'}`,+ }+ : nullconst nativeSource = nativeSources.find((s) => s.id === source.id)if (nativeSource) {const requiredFields =@@ -232,6 +243,9 @@ function getSourceStatus(message: 'One or more required tables sync is cancelled',}}+ if (validationWarning) {+ return validationWarning+ }if (schemaStatuses.length === requiredFields.length &&schemaStatuses.every((status) => status === ExternalDataSchemaStatus.Completed)@@ -250,13 +264,13 @@ function getSourceStatus(const hasMapping = externalTable.source_map && Object.keys(externalTable.source_map).length > 0if (!hasMapping) {- return { status: MarketingSourceStatus.Warning, message: 'Needs column mapping' }+ return validationWarning ?? { status: MarketingSourceStatus.Warning, message: 'Needs column mapping' }}// For sources with schema_status (managed sources like BigQuery)if (externalTable.schema_status) {if (externalTable.schema_status === ExternalDataSchemaStatus.Completed) {- return { status: ExternalDataSchemaStatus.Completed, message: 'Ready to use' }+ return validationWarning ?? { status: ExternalDataSchemaStatus.Completed, message: 'Ready to use' }}if (externalTable.schema_status === ExternalDataSchemaStatus.Failed) {return { status: ExternalDataSchemaStatus.Failed, message: 'Table sync failed' }@@ -272,8 +286,7 @@ function getSourceStatus(}}- // For self-managed sources having a mapping means it's ready- return { status: ExternalDataSchemaStatus.Completed, message: 'Ready to use' }+ return validationWarning ?? { status: ExternalDataSchemaStatus.Completed, message: 'Ready to use' }}return { status: MarketingSourceStatus.Error, message: 'Unknown source status' }@@ -335,11 +348,11 @@ export interface marketingAnalyticsLogicValues {allAvailableSourcesWithStatus: {id: stringname: string- prefix?: string | undefined+ prefix: string | undefinedsource_type: stringstatus: SourceStatusstatusMessage: string- type: string+ type: DataWarehouseSettingsTab | 'native'}[]allExternalTablesWithStatus: {columns: {@@ -391,6 +404,10 @@ export interface marketingAnalyticsLogicValues {overviewQuery: MarketingAnalyticsAggregatedQuerysetupSection: SetupSectionshouldFilterTestAccounts: boolean+ sourceValidation: SourceValidationApi+ sourceValidationError: string | null+ sourceValidationErrors: SourceValidationApi['errors_by_source']+ sourceValidationLoading: booleantileColumnSelection: validColumnsForTilesunconfiguredNativeSources: ExternalDataSource[]uniqueConversionGoalName: string@@ -477,6 +494,21 @@ export interface marketingAnalyticsLogicActions {loadConversionGoal: (goal: ConversionGoalFilter) => {goal: ConversionGoalFilter}+ loadSourceValidation: (_: void) => void+ loadSourceValidationFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSourceValidationSuccess: (+ sourceValidation: SourceValidationApi,+ payload?: void+ ) => {+ sourceValidation: SourceValidationApi+ payload?: void+ }openSetup: (section: SetupSection,entryPoint: SetupEntryPoint@@ -666,24 +698,36 @@ export interface marketingAnalyticsLogicMeta {source_type: stringtype: string}[]+ sourceValidationErrors: (sourceValidation: SourceValidationApi) => SourceValidationApi['errors_by_source']allAvailableSourcesWithStatus: (- allAvailableSources: {+ allExternalTablesWithStatus: {+ columns: {+ name: string+ type: string+ }[]+ dw_source_type: string+ external_type: DataWarehouseSettingsTabid: stringname: string- prefix?: string | undefined+ schema_name: string+ schema_status?: string | undefined+ source_map: SourceMap | null+ source_map_id: string+ source_prefix: stringsource_type: string- type: string- }[],- nativeSources: ExternalDataSource[],- validExternalTables: ExternalTable[]+ sourceUrl: string+ status: SourceStatus+ statusMessage: string+ url_pattern: string+ }[]) => {id: stringname: string- prefix?: string | undefined+ prefix: string | undefinedsource_type: stringstatus: SourceStatusstatusMessage: string- type: string+ type: DataWarehouseSettingsTab | 'native'}[]hasNoConfiguredSources: (validExternalTables: ExternalTable[],@@ -694,7 +738,8 @@ export interface marketingAnalyticsLogicMeta {hasSources: (validExternalTables: ExternalTable[], validNativeSources: NativeSource[]) => booleanallExternalTablesWithStatus: (externalTables: ExternalTable[],- nativeSources: ExternalDataSource[]+ nativeSources: ExternalDataSource[],+ sourceValidationErrors: import('products/marketing_analytics/frontend/generated/api.schemas').SourceValidationApiErrorsBySource) => {columns: {name: string@@ -768,6 +813,21 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([['addProductIntent'],],})),+ loaders(() => ({+ sourceValidation: [+ { errors_by_source: {} } as SourceValidationApi,+ {+ loadSourceValidation: async (_: void, breakpoint) => {+ await breakpoint(100)+ const result = await marketingAnalyticsSourceValidationRetrieve(+ String(teamLogic.values.currentTeamId)+ )+ breakpoint()+ return result+ },+ },+ ],+ })),actions({setAdPerformanceConversionGoals: (include: boolean) => ({ include }),setActiveTab: (tab: MarketingAnalyticsTab) => ({ tab }),@@ -835,6 +895,13 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([const persistConfig = buildTeamScopedPersistenceConfig()return {+ sourceValidationError: [+ null as string | null,+ {+ loadSourceValidationSuccess: () => null,+ loadSourceValidationFailure: (_, { error }) => error,+ },+ ],adPerformanceConversionGoals: [true, { setAdPerformanceConversionGoals: (_, { include }) => include }],activeTab: [MarketingAnalyticsTab.DASHBOARD as MarketingAnalyticsTab,@@ -1300,57 +1367,25 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([return sources},],+ sourceValidationErrors: [+ (s) => [s.sourceValidation],+ (sourceValidation: SourceValidationApi): SourceValidationApi['errors_by_source'] =>+ sourceValidation.errors_by_source,+ ],allAvailableSourcesWithStatus: [- (s) => [s.allAvailableSources, s.nativeSources, s.validExternalTables],- (- allAvailableSources: {- id: string- name: string- prefix?: string | undefined- source_type: string- type: string- }[],- nativeSources: ExternalDataSource[],- validExternalTables: ExternalTable[]- ) => {- const sourcesWithStatus = allAvailableSources.map((source) => {- const status = getSourceStatus(source, nativeSources, validExternalTables)- return {- ...source,- status: status.status,- statusMessage: status.message,- }- })-- // Also include native sources not in allAvailableSources (those with- // disabled/missing tables) so the banner can surface warnings for them- const includedIds = new Set(allAvailableSources.map((s) => s.id))- nativeSources.forEach((source) => {- if (!includedIds.has(source.id)) {- const status = getSourceStatus(- {- id: source.id,- name: source.source_type,- type: 'native',- prefix: source.prefix ?? undefined,- },- nativeSources,- validExternalTables- )- sourcesWithStatus.push({- id: source.id,- name: source.source_type,- type: 'native',- source_type: source.source_type,- prefix: source.prefix ?? undefined,- status: status.status,- statusMessage: status.message,- })- }- })-- return sourcesWithStatus- },+ (s) => [s.allExternalTablesWithStatus],+ (tables: (ExternalTable & { status: SourceStatus; statusMessage: string; isNativeSource?: boolean })[]) =>+ tables+ .filter((table) => table.isNativeSource || table.source_map !== null)+ .map((table) => ({+ id: table.source_map_id,+ name: table.schema_name,+ type: table.isNativeSource ? 'native' : table.external_type,+ source_type: table.source_type,+ prefix: table.source_prefix || undefined,+ status: table.status,+ statusMessage: table.statusMessage,+ })),],hasNoConfiguredSources: [(s) => [s.validExternalTables, s.validNativeSources, s.loading, s.dataWarehouseTables],@@ -1373,8 +1408,12 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([validExternalTables.length > 0 || validNativeSources.length > 0,],allExternalTablesWithStatus: [- (s) => [s.externalTables, s.nativeSources],- (externalTables: ExternalTable[], nativeSources: ExternalDataSource[]) => {+ (s) => [s.externalTables, s.nativeSources, s.sourceValidationErrors],+ (+ externalTables: ExternalTable[],+ nativeSources: ExternalDataSource[],+ validationErrors: SourceValidationApi['errors_by_source']+ ) => {// Filter out tables that belong to native sources (to avoid duplicates)// Only include BigQuery, self-managed, and other non-native sources// For example a native source could have multiple external tables.@@ -1392,7 +1431,8 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([prefix: table.source_prefix,},[],- nonNativeTables+ nonNativeTables,+ validationErrors)return {...table,@@ -1406,7 +1446,8 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([const status = getSourceStatus({ id: source.id, name: source.source_type, type: 'native', prefix: source.prefix ?? undefined },nativeSources,- []+ [],+ validationErrors)// Convert native source to ExternalTable format for unified handling@@ -1669,7 +1710,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([setChartDisplayType: trackDashboardInteraction,setTileColumnSelection: trackDashboardInteraction,setDrillDownLevel: trackDashboardInteraction,- reloadAll: trackDashboardInteraction,+ reloadAll: [trackDashboardInteraction, () => actions.loadSourceValidation()],applyConversionGoal: [() => {const goal = {diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.pyindex b3f89f720142..8b9a3f55c675 100644--- a/products/marketing_analytics/backend/api.py+++ b/products/marketing_analytics/backend/api.py@@ -29,6 +29,7 @@ from rest_framework.viewsets import GenericViewSetfrom posthog.schema import ConversionGoalFilter1, ConversionGoalFilter2, ConversionGoalFilter3, DateRange, SourceMapfrom posthog.hogql import ast+from posthog.hogql.database.database import Databasefrom posthog.hogql.query import execute_hogql_queryfrom posthog.api.documentation import _FallbackSerializer@@ -429,6 +430,13 @@ class ConversionGoalWriteResponseSerializer(serializers.Serializer):# --- list_data_sources ---+class SourceValidationSerializer(serializers.Serializer):+ errors_by_source = serializers.DictField(+ child=serializers.ListField(child=serializers.CharField()),+ help_text="Validation errors keyed by the source or mapped table ID. Valid sources are omitted.",+ )++class DataSourcesQuerySerializer(serializers.Serializer):source_type = serializers.CharField(required=False,@@ -1323,6 +1331,23 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):context=self.get_serializer_context(),)+ @validated_request(+ responses={200: SourceValidationSerializer},+ summary="Validate marketing sources",+ description="Check connected marketing sources using the same validators as campaign queries. Read-only.",+ )+ @action(methods=["GET"], detail=False, url_path="source_validation", required_scopes=["marketing_analytics:read"])+ def source_validation(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ factory = MarketingSourceFactory(+ context=QueryContext(+ date_range=None,+ team=self.team,+ database=Database.create_for(team=self.team, user=cast(User, request.user)),+ )+ )+ errors = factory.get_validation_errors(factory.create_adapters(raise_on_error=True))+ return Response(SourceValidationSerializer({"errors_by_source": errors}).data)+@validated_request(query_serializer=DataSourcesQuerySerializer,responses={diff --git a/products/marketing_analytics/backend/hogql_queries/adapters/factory.py b/products/marketing_analytics/backend/hogql_queries/adapters/factory.pyindex b4f38ba61b9e..9bd33298e2a8 100644--- a/products/marketing_analytics/backend/hogql_queries/adapters/factory.py+++ b/products/marketing_analytics/backend/hogql_queries/adapters/factory.py@@ -196,7 +196,7 @@ class MarketingSourceFactory:"""Register a new adapter type for a marketing source"""cls._adapter_registry[source_type] = adapter_class- def create_adapters(self) -> list[MarketingSourceAdapter]:+ def create_adapters(self, *, raise_on_error: bool = False) -> list[MarketingSourceAdapter]:"""Discover all available marketing sources and create adapters for them."""try:adapters = []@@ -208,6 +208,8 @@ class MarketingSourceFactory:except Exception as e:self.logger.exception("Error creating marketing source adapters", error=str(e))+ if raise_on_error:+ raisereturn []def _create_native_adapters(self) -> list[MarketingSourceAdapter]:@@ -424,6 +426,21 @@ class MarketingSourceFactory:self.logger.exception("Error validating adapter", source_type=adapter.get_source_type(), error=str(e))return valid_adapters+ def get_validation_errors(self, adapters: list[MarketingSourceAdapter]) -> dict[str, list[str]]:+ errors_by_source: dict[str, list[str]] = {}+ for adapter in adapters:+ try:+ result = adapter.validate()+ if not result.is_valid:+ errors_by_source[adapter.config.source_id] = [+ error if not error.startswith("Validation error:") else "Source validation failed."+ for error in result.errors+ ] or ["Source validation failed."]+ except Exception:+ self.logger.exception("Error validating adapter", source_type=adapter.get_source_type())+ errors_by_source[adapter.config.source_id] = ["Source validation failed."]+ return errors_by_source+def build_union_query_ast(self, adapters: list[MarketingSourceAdapter]) -> ast.SelectQuery | ast.SelectSetQuery:"""Build union query AST from all valid adapters.diff --git a/products/marketing_analytics/backend/hogql_queries/adapters/test_factory.py b/products/marketing_analytics/backend/hogql_queries/adapters/test_factory.pyindex da5ace90dbf0..c1dfcf5cbbf7 100644--- a/products/marketing_analytics/backend/hogql_queries/adapters/test_factory.py+++ b/products/marketing_analytics/backend/hogql_queries/adapters/test_factory.py@@ -564,7 +564,7 @@ class TestNativeCampaignTableResolution(FactoryTestMixin, BaseTest):class TestNativeSourceKillSwitch(SimpleTestCase):@parameterized.expand([(False,), (True,)])- def test_factory_excludes_disabled_source_without_affecting_google(self, enabled: bool) -> None:+ def test_factory_excludes_disabled_sources_from_discovery_and_validation(self, enabled: bool) -> None:team = Team(id=1)factory = MarketingSourceFactory.__new__(MarketingSourceFactory)factory.context = Mock(spec=QueryContext, team=team)@@ -592,4 +592,7 @@ class TestNativeSourceKillSwitch(SimpleTestCase):assert [adapter.get_source_type() for adapter in adapters] == (["GoogleAds", "AppleSearchAds", "OpenAIAds", "AmazonAds", "RoktAds"] if enabled else ["GoogleAds"])+ errors = factory.get_validation_errors(adapters)+ assert set(errors) == ({adapter.config.source_id for adapter in adapters[1:]} if enabled else set())+ assert all(messages for messages in errors.values())factory.logger.exception.assert_not_called()diff --git a/products/marketing_analytics/frontend/dashboard/MarketingAnalyticsSourceStatusBanner.stories.tsx b/products/marketing_analytics/frontend/dashboard/MarketingAnalyticsSourceStatusBanner.stories.tsxnew file mode 100644index 000000000000..0133d9000d0d--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/MarketingAnalyticsSourceStatusBanner.stories.tsx@@ -0,0 +1,104 @@+import type { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { MarketingAnalyticsSourceStatusBanner } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsSourceStatusBanner'++import { mswDecorator } from '~/mocks/browser'+import { DatabaseSchemaDataWarehouseTable, MARKETING_INTEGRATION_CONFIGS } from '~/queries/schema/schema-general'++const table: DatabaseSchemaDataWarehouseTable = {+ id: 'example-insights-table',+ name: 'openai_campaign_insights',+ type: 'data_warehouse',+ schema: { id: 'example-insights', name: 'campaign_insights', should_sync: true, incremental: false },+ fields: Object.fromEntries(+ ['campaign_id', 'start_time', 'impressions', 'clicks', 'spend'].map((name) => [+ name,+ { name, hogql_value: name, type: 'string', schema_valid: true },+ ])+ ),+}++const meta: Meta<typeof MarketingAnalyticsSourceStatusBanner> = {+ title: 'Scenes-App/Marketing Analytics/Source status',+ component: MarketingAnalyticsSourceStatusBanner,+ render: () => (+ <div id="source-status-snapshot" className="w-200 max-w-[calc(100vw-2rem)]">+ <MarketingAnalyticsSourceStatusBanner />+ </div>+ ),+ parameters: {+ featureFlags: [FEATURE_FLAGS.MARKETING_ANALYTICS_OPENAI_ADS],+ testOptions: {+ waitForSelector: '[data-attr="marketing-source-status-settings"][href*="managed-example-openai-source"]',+ snapshotTargetSelector: '#source-status-snapshot',+ },+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/marketing_analytics/source_validation/': () => [+ 200,+ {+ errors_by_source: {+ 'example-openai-source': [+ "OpenAI Ads is missing 'currency_code' in 'openai_campaign_insights'. Sync this table again.",+ ],+ },+ },+ ],+ '/api/projects/:team_id/external_data_sources/wizard/': () => [200, {}],+ '/api/environments/:team_id/external_data_sources/': () => [+ 200,+ {+ count: 2,+ next: null,+ previous: null,+ results: [+ {+ id: 'example-google-source',+ source_type: 'GoogleAds',+ status: 'Cancelled',+ schemas: [+ MARKETING_INTEGRATION_CONFIGS.GoogleAds.campaignTableName,+ MARKETING_INTEGRATION_CONFIGS.GoogleAds.statsTableName,+ ].map((name) => ({+ id: `example-google-${name}`,+ name,+ should_sync: true,+ status: 'Cancelled',+ })),+ },+ {+ id: 'example-openai-source',+ source_type: 'OpenAIAds',+ status: 'Completed',+ schemas: [+ {+ id: 'example-campaigns',+ name: 'campaigns',+ should_sync: true,+ status: 'Completed',+ },+ {+ id: 'example-insights',+ name: 'campaign_insights',+ should_sync: true,+ status: 'Completed',+ },+ ],+ },+ ],+ },+ ],+ },+ post: {+ '/api/environments/:team_id/query/:kind': () => [200, { tables: { [table.name]: table }, joins: [] }],+ },+ }),+ ],+}+export default meta++type Story = StoryObj<typeof MarketingAnalyticsSourceStatusBanner>+export const SourceIssues: Story = {}diff --git a/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsx b/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsxindex 0051018caf28..5e6f41ac9ffd 100644--- a/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsx+++ b/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsx@@ -13,6 +13,7 @@ import { teamLogic } from 'scenes/teamLogic'import { MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS } from 'scenes/web-analytics/common'import { AttributionTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab'import { AttributionTable } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable'+import { MarketingAnalyticsSourceStatusBanner } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsSourceStatusBanner'import { RetentionTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionTab'import {SetupSection,@@ -192,6 +193,7 @@ export function NewMarketingAnalyticsDashboard(): JSX.Element {</>)}</div>+ <MarketingAnalyticsSourceStatusBanner /><div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,24rem),1fr))] items-start gap-2 empty:hidden">{sourceSuggestions.length > 0 && (<div className="border rounded relative">diff --git a/products/marketing_analytics/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.tsindex 0170b70b7553..fda9a9a7ea45 100644--- a/products/marketing_analytics/frontend/generated/api.schemas.ts+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts@@ -1647,6 +1647,16 @@ export interface SetupPlanResponseApi {summary: string}+/**+ * Validation errors keyed by the source or mapped table ID. Valid sources are omitted.+ */+export type SourceValidationApiErrorsBySource = { [key: string]: string[] }++export interface SourceValidationApi {+ /** Validation errors keyed by the source or mapped table ID. Valid sources are omitted. */+ errors_by_source: SourceValidationApiErrorsBySource+}+export interface CandidateEventApi {/** Name of the candidate event */event_name: stringdiff --git a/products/marketing_analytics/frontend/generated/api.ts b/products/marketing_analytics/frontend/generated/api.tsindex 6a805122cf6f..1c618f7589ab 100644--- a/products/marketing_analytics/frontend/generated/api.ts+++ b/products/marketing_analytics/frontend/generated/api.ts@@ -27,6 +27,7 @@ import type {MarketingDiagnosticResponseApi,PatchedConversionGoalUpdateApi,SetupPlanResponseApi,+ SourceValidationApi,UtmAuditResponseApi,UtmMappingSuggestionsResponseApi,} from './api.schemas'@@ -277,6 +278,24 @@ export const marketingAnalyticsSetupPlanRetrieve = async (})}+export const getMarketingAnalyticsSourceValidationRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/marketing_analytics/source_validation/`+}++/**+ * Check connected marketing sources using the same validators as campaign queries. Read-only.+ * @summary Validate marketing sources+ */+export const marketingAnalyticsSourceValidationRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<SourceValidationApi> => {+ return apiMutator<SourceValidationApi>(getMarketingAnalyticsSourceValidationRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}+export const getMarketingAnalyticsSuggestConversionGoalsRetrieveUrl = (projectId: string,params?: MarketingAnalyticsSuggestConversionGoalsRetrieveParamsdiff --git a/products/marketing_analytics/mcp/tools.yaml b/products/marketing_analytics/mcp/tools.yamlindex 267cc23a22dd..d8226f9a5198 100644--- a/products/marketing_analytics/mcp/tools.yaml+++ b/products/marketing_analytics/mcp/tools.yaml@@ -123,6 +123,9 @@ tools:marketing-analytics-setup-plan-retrieve:operation: marketing_analytics_setup_plan_retrieveenabled: false+ marketing-analytics-source-validation-retrieve:+ operation: marketing_analytics_source_validation_retrieve+ enabled: falsemarketing-analytics-suggest-conversion-goals:operation: marketing_analytics_suggest_conversion_goals_retrieveenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4309d48f3c06..15793bbbaadc 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -97221,6 +97221,16 @@ export namespace Schemas {webhook?: SourceSetupWebhook;}+ /**+ * Validation errors keyed by the source or mapped table ID. Valid sources are omitted.+ */+ export type SourceValidationErrorsBySource = {[key: string]: string[]};++ export interface SourceValidation {+ /** Validation errors keyed by the source or mapped table ID. Valid sources are omitted. */+ errors_by_source: SourceValidationErrorsBySource;+ }+/*** The setup task that was started for the channel.*/